78. Subsets
Difficulty: Medium
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
1 | [ |
求一个集合的所有子集
错误:
- 忘记返回值
- 递归忘记返回
- List是引用传参,改为string
Solution
1 | class Solution { |
使用List1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(null==nums || nums.length==0)return res;
List<Integer> temp=new ArrayList<>();
helper(res, nums, temp, 0);
return res;
}
public void helper(List<List<Integer>> list, int[] nums, List<Integer> temp, int cur){
if(cur >= nums.length){
// add temp to list
list.add(new ArrayList<>(temp));
return;
}
// don't add nums[cur]
helper(list, nums, temp, cur+1);
// add nums[cur]
temp.add(nums[cur]);
helper(list, nums, temp, cur+1);
temp.remove(temp.indexOf(nums[cur]));
}
}