leetcode(78) subsets 解法

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

解法

这道题与之前combination那题基本解法一样,采用深度优先遍历,用开始参数向后搜索确保不重复,注意搜索完成后的回溯。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class  {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();

public List<List<Integer>> subsets(int[] nums) {
int n = nums.length;
for (int i = 0; i <= n; i++) {
helper(nums, 0, i);
}
return res;
}

void helper(int[] nums, int start, int len) {
if (tmp.size() == len) {
List<Integer> add = new ArrayList<>();
for (int i = 0; i < tmp.size(); i++) {
add.add(tmp.get(i));
}
res.add(add);
return;
}
for (int i = start; i < nums.length; i++) {
tmp.add(nums[i]);
helper(nums, i + 1, len);
tmp.remove((Integer) nums[i]);
}
}
}