给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: [1,2,2] 输出: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]
和I不同的是,本题的数组,可以有重复元素。我们可以用下面两行代码过滤重复元素。
while(i+1<nums.length && nums[i] == nums[i+1])
i++;
这就要求我们重复元素是连续出现的,即数组是有序的。所以在第一次调用helper()时,我们要先将数组排序。
成功
执行用时 : 1 ms, 在Subsets II的Java提交中击败了100.00% 的用户
内存消耗 : 35.7 MB, 在Subsets II的Java提交中击败了96.31% 的用户
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer> >();
List<Integer> tmp = new ArrayList<Integer>();
//空集是任意集合的子集
res.add(tmp);
if(nums.length == 0)
return res;
Arrays.sort(nums);//[4,4,4,1,4]
helper(nums, 0, tmp, res);
return res;
}
public void helper(int[] nums, int start, List<Integer> tmp, List<List<Integer>> res){
for(int i=start; i<nums.length; i++){
tmp.add(nums[i]);
helper(nums, i+1, tmp, res);
res.add(new ArrayList<Integer>(tmp));
tmp.remove(tmp.size()-1 );
while(i+1<nums.length && nums[i] == nums[i+1])
i++;
}
}
}