Subsets II
Given a collection of integers that might contain duplicates, S, return all possible subsets.
If S = [1,2,2]
, a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
1 public class Solution{ 2 public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) { 3 Arrays.sort(num); 4 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 5 res.add(new ArrayList<Integer>()); 6 if(num.length<=0) return res; 7 DFS(num,0,new ArrayList<Integer>(),res); 8 return res; 9 } 10 public void DFS(int []num,int start,ArrayList<Integer>output,ArrayList<ArrayList<Integer>>res ){ 11 for(int i=start;i<num.length;i++){ 12 ArrayList<Integer>temp = new ArrayList<Integer>(); 13 output.add(num[i]); 14 temp.addAll(output); 15 res.add(temp); 16 DFS(num,i+1,output,res); 17 output.remove(output.size()-1); 18 while(i<num.length-1 && num[i]==num[i+1]){ 19 i++; 20 } 21 } 22 } 23 }