Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2]
, a solution
is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
DFS
public class Solution {
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
Arrays.sort(num);
ArrayList<Integer> list = new ArrayList<Integer>();
dfs(res,0,num,list);
return res;
}
private void dfs(ArrayList<ArrayList<Integer>> res,int index,int[] num,ArrayList<Integer> list) {
ArrayList<Integer> tmp = new ArrayList<Integer>(list);
res.add(tmp);
int pre=0;
for(int i=index;i<num.length;i++){
if(i==index)
pre=num[index]-1;
if(pre==num[i])
continue;
list.add(num[i]);
dfs(res, i+1, num, list);
list.remove(list.size()-1);
pre=num[i];
}
}
}