问题描述
- Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
- Note: The solution set must not contain duplicate subsets.
- Example :
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
问题分析
- LeetCode 78. Subsets 的进阶题,只是该题可能含有重复元素,所以必须要去重
- 采用类似于在类似于寻找组合的过程中,不断向结果集中添加中间路径。 并保证去重,去重的方法和 Combination Sum II 一致
代码实现
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<>();
}
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
findSubSet(nums, 0, new ArrayList<>(), res);
return res;
}
public void findSubSet(int[] nums, int i, ArrayList<Integer> path, List<List<Integer>> res){
res.add(new ArrayList<>(path));
for (int j = i; j < nums.length; ++j) {
if (j > i && nums[j] == nums[j - 1]) {
continue;
}
path.add(nums[j]);
findSubSet(nums, j + 1, path, res);
path.remove(path.size() - 1);
}
}
}