问题
给你一个整数数组 nums
,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)
解集不能包含重复的子集。返回的解集中,子集可以按任意顺序排列
示例 1:
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
思路
用示例中的[1, 2, 2]
来举例,如图所示:注意去重需要先对集合排序
从图中可以看出,同一树层上重复取2
就要过滤掉,同一树枝上就可以重复取2
,因为同一树枝上元素的集合才是唯一子集!
class Solution {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<>();
public void backtracking(int[] nums, int startIndex, boolean[] used) {
result.add(new ArrayList<>(path));
for (int i = startIndex; i < nums.length; i++) {
// used[i - 1] == true,说明同一树支candidates[i - 1]使用过
// used[i - 1] == false,说明同一树层candidates[i - 1]使用过
// 而我们要对同一树层使用过的元素进行跳过
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
continue;
}
path.add(nums[i]);
used[i] = true;
backtracking(nums, i + 1, used);
used[i] = false;
path.remove(path.size() - 1);
}
}
public List<List<Integer>> subsetsWithDup(int[] nums) {
boolean[] used = new boolean[nums.length];
Arrays.sort(nums);
backtracking(nums, 0, used);
return result;
}
}
List<List<Integer>> result = new ArrayList<List<Integer>>();
可行List<List<Integer>> result = new ArrayList<>();
可行List<List<Integer>> result = new ArrayList<List<>>();
不可行