问题背景
给你一个整数数组
n
u
m
s
nums
nums,其中可能包含重复元素,请你返回该数组所有可能的 子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
数据约束
●
1
≤
n
u
m
s
.
l
e
n
g
t
h
≤
10
1 \le nums.length \le 10
1≤nums.length≤10
●
−
10
≤
n
u
m
s
[
i
]
≤
10
-10 \le nums[i] \le 10
−10≤nums[i]≤10
解题过程
经典回溯问题,在 没有重复元素的版本 实现的基础上,跳过重复元素就可以了。
具体实现
选或不选
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs(0, nums, res, path);
return res;
}
private void dfs(int i, int[] nums, List<List<Integer>> res, List<Integer> path) {
int n = nums.length;
if (i == n) {
res.add(new ArrayList<>(path));
return;
}
int cur = nums[i];
path.add(cur);
dfs(i + 1, nums, res, path);
path.remove(path.size() - 1);
i++;
while (i < n && nums[i] == cur) {
i++;
}
dfs(i, nums, res, path);
}
}
选哪一个
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs(0, nums, res, path);
return res;
}
private void dfs(int i, int[] nums, List<List<Integer>> res, List<Integer> path) {
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]);
dfs(j + 1, nums, res, path);
path.remove(path.size() - 1);
}
}
}