Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- 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], [] ]
思路:这个与I的区别就是里面有重复的数字,我们可以通过set<List<Integer>>过滤下重复的List<Integer>就行
代码如下(已通过leetcode)
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> lists=new ArrayList<List<Integer>>();
List<Integer> list=new ArrayList<Integer>();
lists.add(list);
int n=nums.length;
if(n==0||nums==null) return lists;
Set<List<Integer>> sets=new HashSet<List<Integer>>();
Arrays.sort(nums);
for(int i=1;i<=n;i++) {
dfs(nums,sets,list,0,i);
}
//System.out.println("sets:"+sets.size());
Iterator<List<Integer>> it=sets.iterator();
while(it.hasNext()) {
lists.add(it.next());
}
return lists;
}
private void dfs(int[] nums, Set<List<Integer>> sets, List<Integer> list, int start, int number) {
// TODO Auto-generated method stub
if(number==list.size()) {
sets.add(new ArrayList<Integer>(list));
return;
}
for(int i=start;i<nums.length;i++) {
list.add(nums[i]);
dfs(nums,sets,list,i+1,number);
list.remove(list.size()-1);
}
}
}