子集Ⅱ

90. 子集 II

给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。

示例 1:

1
2
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]

示例 2:

1
2
输入:nums = [0]
输出:[[],[0]]

提示:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10

解题思路

同组合总和II

在同一个树层去重可以防止出现重复的组合,需要到nums进行排序

如果当前元素与前一个元素相同,且前一个元素已完成递归,则需要去重

使用used数组判断

  • used[i - 1] == true,说明同一树枝used[i - 1]使用过
  • used[i - 1] == false,说明同一树层used[i - 1]使用过

image-20230824114405474

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
LinkedList<Integer> path = new LinkedList<>();// 用来存放符合条件结果
boolean[] used;

public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
used = new boolean[nums.length];
traversal(nums, 0);
return result;
}

private void traversal(int[] nums, int startIndex){
result.add(new ArrayList<>(path));
if (startIndex >= nums.length){
return;
}
for (int i = startIndex; i < nums.length; i++){
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false){
continue;
}
path.add(nums[i]);
used[i] = true;
traversal(nums, i + 1);
path.removeLast();
used[i] = false;
}
}
}

不使用used数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
backtracking(nums,0);
return res;
}


public void backtracking(int[] nums, int index){
res.add(new ArrayList<>(path)); //遍历的时候,把所有子集都记录下来
if(index==nums.length){
return;
}
for(int i = index ; i<nums.length; i++){
if(i>index&&nums[i]==nums[i-1]) continue; //跳过同一层重复的元素选取
path.add(nums[i]);
backtracking(nums,i+1); //递归
path.remove(path.size()-1);//回溯
}
}
}

子集Ⅱ
http://example.com/2023/05/04/算法/回溯/9. 子集 II/
作者
PALE13
发布于
2023年5月4日
许可协议