p78

LeetCode p78 Subsets 题解

1.题目:

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

题意:

返回一个数组所有的子集。

2.解题思路:

dp

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
dp(ans, nums, 0, list);
return ans;
}
public void dp(List<List<Integer>> ans, int[] nums, int start,
List<Integer> list) {
if (start > nums.length)
return;
ans.add(new ArrayList<Integer>(list));
for (int i = start; i < nums.length; i++) {
list.add(nums[i]);
dp(ans, nums, i + 1, list);
list.remove(list.size() - 1);

}
}
}

4.一些总结: