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.
Example:
Input: [1,2,2] Output: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]
解法:
炒冷饭了。记得两点:
1、先排序
2、跳过相同的数
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> inner = new ArrayList<>();
//先排序
Arrays.sort(nums);
findAns(res,inner,0,nums);
return res;
}
public void findAns(List<List<Integer>> res, List<Integer> inner, int index, int[]nums){
List<Integer> tmp = new ArrayList<>(inner);
res.add(tmp);
for(int i=index;i<nums.length;i++){
inner.add(nums[i]);
findAns(res,inner,i+1,nums);
inner.remove(inner.size()-1);
//判断重复
while(i<nums.length-1 && nums[i]==nums[i+1]) i++;
}
}
}