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],
[]
]
题意:给定数组,可能有重复元素,求其所有可能的自己(Subsets的去重)
解决思路:记录一下重复数的个数,对其特别处理下就可以
代码:
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
result.add(new ArrayList<Integer>());
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
int dup = 0;
while((i + 1) < nums.length && nums[i + 1] == nums[i]){
dup++;
i++;
}
int currSize = result.size();
for(int j = 0; j < currSize; j++){
List<Integer> temp = new ArrayList<Integer>(result.get(j));
for(int t = 0; t <= dup; t++){
temp.add(nums[i]);
result.add(new ArrayList<Integer>(temp));
}
}
}
return result;
}
}