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], [] ]
和上一篇Subsets一样,只不过序列中有重复元素,但是要保证输出结果不包含重复集合。
解题思路:只取第一个相同元素加入组合里就可以了
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
//对数列进行排序
Arrays.sort(nums);
//创建结果集
List<List<Integer>> resSet = new ArrayList<List<Integer>>();
helper(nums, 0, new ArrayList<Integer>(), resSet);
return resSet;
}
public void helper(int[] nums,int start,
List<Integer> subset,List<List<Integer>> resSet) {
if (start > nums.length) {
return;
}
//保留中间任意结果
List<Integer> clone = new ArrayList<Integer>(subset);
resSet.add(clone);
for (int i = start; i < nums.length; i++) {
if (i != start && nums[i] == nums[i-1]) continue;
subset.add(nums[i]);//加入新元素并递归调用下一个元素
helper(nums, i+1, subset, resSet);;
subset.remove(subset.size()-1);//回退
}
}
}