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], [] ]
Backtrack就完事了,记得先排序一下,结果:
Success
Runtime: 1 ms, faster than 99.06% of Java online submissions for Subsets II.
Memory Usage: 37.5 MB, less than 98.53% of Java online submissions forSubsets II.
class Solution {
private List<List<Integer>> res;
public List<List<Integer>> subsetsWithDup(int[] nums) {
res=new ArrayList<>();
ArrayList<Integer> temp=new ArrayList<>();
res.add(new ArrayList<>(temp));
if(nums==null||nums.length==0){return res;}
Arrays.sort(nums);
findsubs(nums,temp,0);
return res;
}
private void findsubs(int[] nums,List<Integer> cur,int bound){
for(int i=bound;i<nums.length;i++){
cur.add(nums[i]);
res.add(new ArrayList<>(cur));
findsubs(nums,cur,i+1);
cur.remove(cur.size()-1);
while((i+1)<nums.length&&nums[i+1]==nums[i]){i++;}
}
}
}