Description
Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Examples
Example 1:
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
思路1及对应代码
最开始的时候是用 #78 subsets 里面的思路2,但是因为有重复数据,所以要用Set做存储,最后转为List即可
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Set<List<Integer>> toAdd = new HashSet<>();
Set<List<Integer>> answer = new HashSet<>();
Arrays.sort(nums);
toAdd.add(new ArrayList<>());
answer.add(new ArrayList<>());
for(int i = 0; i < nums.length; i++){
for(List<Integer> temp: toAdd){
List<Integer> t = new ArrayList<>(temp);
t.add(nums[i]);
answer.add(new ArrayList<>(t));
}
toAdd.addAll(answer);
}
return new ArrayList<>(answer);
}
}
思路2及对应代码
思路2在于处理重复数据的方式,也就不用Set进行数据存储,而是通过先对重复数据进行处理的方法
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> answer = new ArrayList<>();
Arrays.sort(nums);
answer.add(new ArrayList<>());
for(int i = 0; i < nums.length; i++){
int count = 1;
while(i < nums.length - 1 && nums[i] == nums[i + 1]){
count ++;
i++;
}
int s = answer.size();
for(int n = 0; n < s; n++){
List<Integer> t = new ArrayList<>(answer.get(n));
for(int j = 0; j < count; j++){
t.add(nums[i]);
answer.add(new ArrayList<>(t));
}
}
}
return answer;
}
}