Subsets II
Given a list of numbers that may has duplicate numbers, return all possible subsets
If S = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
Note
- Each element in a subset must be in non-descending order.
- The ordering between two subsets is free.
- The solution set must not contain duplicate subsets.
Tag
思路
- 在递归条件中直接进行了判断
- 当[1,2,2]后,回到[1,2]后,不再出现[1,2,2];当有[2],[2,2]后不再出现[2],[2,2] 所以这一位跟上一位不能一样 并且同时:
- 但是[1,2,2]与[2,2]是可以出现的,只有顺序输出的12有用,也就是pos==i时
- i = pos的时候, 比如1,2 第三个数 pos=i=2,所以要输出[1,2,2]
- 只有顺序输出的12有用,
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
if (nums == null || nums.length == 0) {
result.add(list);
return result;
}
Arrays.sort(nums);
dfs(result, list, nums, 0);
return result;
}
public void dfs(List<List<Integer>> result, List<Integer> list, int[] nums, int pos) {
result.add(new ArrayList<Integer>(list));
for (int i = pos; i < nums.length; i++) {
if (i != pos && nums[i] == nums[i - 1]) {
continue;
}
list.add(nums[i]);
dfs(result, list, nums, i + 1);
list.remove(list.size() - 1);
}
}
}