题目描述
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
解题思路
这道题是subsets的变种,目前集合中允许有重复的元素,而结果集中不允许有重复的子集合。我是利用一个set来存储已经存在的子集合,通过这种方式实现了去重。
代码
class Solution {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Set<String> set = new HashSet<String>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
result.add(new ArrayList<Integer>());
if(nums == null || nums.length == 0)
return result;
Arrays.sort(nums);
ArrayList<Integer> tmp = new ArrayList<Integer>();
for(int i=1;i<=nums.length;i++){
subsetCore(nums,0,i,tmp);
}
return result;
}
private void subsetCore(int[] nums,int position,int count,List<Integer> tmp){
if(count == 0 ){
if(set.add(tmp.toString())){
result.add(new ArrayList<Integer>(tmp));
}
return;
}
if(nums.length-position < count){
return;
}
for(int i=position;i+count-1<nums.length;i++){
tmp.add(nums[i]);
subsetCore(nums,i+1,count-1,tmp);
tmp.remove(tmp.size()-1);
subsetCore(nums,i+1,count,tmp);
}
}
}