Given a collection of integers that might contain duplicates, nums, return all possible subsets.
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], [] ]要输出排好序的subset,所以先将数组排序。
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> l=new ArrayList<>();
List<Integer> list=new ArrayList<>();
l.add(list);
Arrays.sort(nums);
helper(l,list,nums,0);
return new ArrayList<>(l);
}
public void helper(List<List<Integer>> l,List<Integer> list,int[] nums,int index){
if(index==nums.length) return;
for(int i=index;i<nums.length;i++){
if(i>index&&nums[i]==nums[i-1]) continue;
list.add(nums[i]);
l.add(new ArrayList<>(list));
helper(l,list,nums,i+1);
list.remove(list.size()-1);
}
}
}