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], [] ]
还是DFS的方法,不过没有考虑去重,用了set
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Set<List<Integer>> set = new HashSet<>();
Arrays.sort(nums);
helper(set, new ArrayList(), nums, 0);
List<List<Integer>> ans = new ArrayList(set);
return ans;
}
private void helper(Set<List<Integer>> set, List<Integer> list, int[] nums, int start){
set.add(new ArrayList(list));
for(int i=start; i<nums.length; i++){
if(i > start && nums[i] == nums[i-1]) continue; // add here to skip duplicates
list.add(nums[i]); helper(set, list, nums, i+1); list.remove(list.size()-1); } }}