We can easily use hashset to solve this problem, based on the previous Subset problem.
Code:
public class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { Arrays.sort(nums); int len = nums.length; Set<List<Integer>> set = new HashSet<>(); for(int i = 0; i < len; i++){ List<Integer> list = new ArrayList<>(); addSubset(nums, len-1, 0, i+1, list, set); } List<Integer> list = new ArrayList<>(); set.add(list); return new ArrayList<>(set); } public void addSubset(int[] nums, int n, int cur, int k, List<Integer> list, Set<List<Integer>> set){ if(k == 0){ set.add(new ArrayList<>(list)); return; } list.add(nums[cur]); addSubset(nums, n, cur+1, k-1, list, set); list.remove(list.size()-1); if(cur == n-k+1) return; addSubset(nums, n, cur+1, k, list, set); } }
A way which do not need to use hashset
code:
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
int len = nums.length;
List<List<Integer>> set = new ArrayList<>();
for(int i = 0; i < len; i++){
List<Integer> list = new ArrayList<>();
addSubset(nums, len-1, 0, i+1, list, set);
}
List<Integer> list = new ArrayList<>();
set.add(list);
return set;
}
public void addSubset(int[] nums, int n, int cur, int k, List<Integer> list, List<List<Integer>> set){
if(k == 0){
set.add(new ArrayList<>(list));
return;
}
for(int i = cur; i < nums.length - k + 1; i++){
if(i != cur && nums[i] == nums[i-1]) continue;
list.add(nums[i]);
addSubset(nums, n, i+1, k-1, list, set);
list.remove(list.size()-1);
}
/*
addSubset(nums, n, cur+1, k-1, list, set);
list.remove(list.size()-1);
if(cur == n-k+1) return;
addSubset(nums, n, cur+1, k, list, set);
*/
}
}