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], [] ]
解法和 subset 一样,只是这里有重复值的话需要用 hashset 来避免重复。
public static ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num){
if(num.length ==0) return new ArrayList<>();
Arrays.sort(num);
Set<ArrayList<Integer>> totalSet = new HashSet<>();
ArrayList<Integer> subList = new ArrayList<>();
subsetsWithDupHelper(num,0,subList,totalSet);
return new ArrayList<>(totalSet);
}
private static void subsetsWithDupHelper(int[] num, int i, ArrayList<Integer> subList, Set<ArrayList<Integer>> totalSet){
if(i>=num.length){
totalSet.add(new ArrayList<Integer>(subList));
return;
}
// not choose current num[i]
subsetsWithDupHelper(num,i+1,subList,totalSet);
// choose current num[i]
subList.add(num[i]);
subsetsWithDupHelper(num,i+1,subList,totalSet);
subList.remove(subList.size()-1);
}