题目:
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2]
, a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
思路:
这道题与subsets相比,nums数组中有重复元素,比如nums={1,2,2},那么实际上{1,2(1)}和{1,2(2)}是一样的,如果去重操作在最后res中进行的话,代价太大,比如nums={1,1,1,1,1,1,1,1,1,1}这样的情况,只有11个子集,但是最后形成的res却有1024个子集,代价显然太高。去重即选代表问题,if(i!=pos&&nums[i]==nums[i-1]) continue; if条件表达的意思是当前这个i不是本次遍历的首个数字并且这个数字等于前面的数字,例如nums={1,2(1),2(2)},当subset={1,2(1)}已经加入res,subset里remove掉2(1)之后subset={1},此时pos=1,i=2,nums[2]=nums[1],所以跳过后面的操作,进行下一次循环。
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
List<Integer> subset=new ArrayList<Integer>();
if(nums.length==0)
return res;
Arrays.sort(nums);
helper(res,subset,nums,0);
return res;
}
public void helper(List<List<Integer>> res,List<Integer> subset,int[] nums,int pos){
res.add(new ArrayList<Integer>(subset));
for(int i=pos;i<nums.length;i++){
if(i!=pos&&nums[i]==nums[i-1])
continue;
subset.add(nums[i]);
helper(res,subset,nums,i+1);
subset.remove(subset.size()-1);
}
}
}