给你一个整数数组 nums
,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
示例 1:
示例 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]使用过

代码
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); } } }
|