题目链接
题目描述
给你一个整数数组 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
解题思路
这题和子集那题的区别就是集合里面有重复元素了,而且求取的子集要去重。以示例1为例,如下图所示

从图中可以看出,同一树层上重复取2就要过滤掉,同一树枝上可以重复取2,因为同一树枝元素的集合才是唯一子集
AC代码
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<Integer> path = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
if (nums.length == 0) {
ans.add(new ArrayList<>());
return ans;
}
backTracing(nums, 0, path, ans);
return ans;
}
private static void backTracing(int[] nums, int startIndex, List<Integer> path, List<List<Integer>> ans) {
ans.add(new ArrayList<>(path));
for (int i = startIndex; i < nums.length; i++) {
if(i > startIndex && nums[i] == nums[i-1]){
continue;
}
path.add(nums[i]);
backTracing(nums, i + 1, path, ans);
path.remove(path.size() - 1);
}
}
}
该博客讨论了如何解决LeetCode上的子集II问题,即给定一个可能包含重复元素的整数数组,找出所有不重复的子集。文章通过示例解释了问题,并提供了一种解决方案,通过排序数组和回溯法避免重复子集的生成。AC代码展示了如何实现这一方法。
668

被折叠的 条评论
为什么被折叠?



