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],
[]
]
Solution:
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
ans.add(new ArrayList<Integer>());
Arrays.sort(nums);
int size = ans.size();
for(int i=0; i<nums.length; i++){
List<List<Integer>> newAns = new ArrayList<>();
if(i!=0 && nums[i]==nums[i-1]){
for(int j=0; j<size; j++){
List<Integer> tmp = new ArrayList<>(ans.get(j));
tmp.add(nums[i]);
newAns.add(tmp);
}
} else {
for(int j=0; j<ans.size(); j++){
List<Integer> tmp = new ArrayList<>(ans.get(j));
tmp.add(nums[i]);
newAns.add(tmp);
}
size = ans.size();
}
newAns.addAll(ans);
ans = newAns;
}
return ans;
}
}