90. 子集 II
给你一个整数数组 nums
,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
示例 1:
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
提示:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
思路
做本题之前一定要先做78. 子集。
这道题目和回溯算法:求子集问题!区别就是集合里有重复元素了,而且求取的子集要去重。
那么关于回溯算法中的去重问题,在40.组合总和II中已经详细讲解过了,和本题是一个套路。
理解“树层去重”和“树枝去重”非常重要。
解法
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
if (nums == null || nums.length == 0) {
result.add(new ArrayList<>());
return result;
}
Arrays.sort(nums);
backtracking(nums, 0);
return result;
}
public void backtracking(int[] nums, int start) {
result.add(new ArrayList<>(list));
if (start == nums.length) {
return;
}
boolean[] used = new boolean[nums.length];
for (int i = start; i < nums.length; i++) {
used[i] = true;
// 去重
if (i > 0 && used[i - 1] && nums[i] == nums[i - 1]) {
continue;
}
list.add(nums[i]);
backtracking(nums, i + 1);
list.remove(list.size() - 1);
}
}
}