给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
思路: 这题必须去重 ,原先去重的方法是 i >0 && nums[i ] == nums[i-1]
这样会把正确的思路给去掉,其实可以放入HashSet即可。
还有就是 添加 i>start && nums[i] == nums[i-1] 这样既保证在当前层去重,在下一层时保留正确的答案。
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> list = new ArrayList<>();
if (nums == null || nums.length == 0)
return list;
dfs(list,new ArrayList<Integer>(),0,nums);
return list;
}
public void dfs(List<List<Integer>> list,List<Integer> tmp,int start,int[] nums) {
list.add(new ArrayList<Integer>(tmp));
for (int i = start;i < nums.length;i++) {
if (i > start && nums[i] == nums[i-1])continue;
tmp.add(nums[i]);
dfs(list,tmp,i+1,nums);
tmp.remove(tmp.size()-1);
}
}
}