Leetcode 90.子集II
题目要求
示例 1:
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
回溯法

树层去重在for循环内设置终止条件
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 { private List<List<Integer>> res = new ArrayList<List<Integer>>(); private 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 startIndex) {
res.add(new ArrayList<>(path));
if (startIndex >= nums.length) return; for (int i = startIndex; i < nums.length; i++) { if (i > startIndex && nums[i] == nums[i -1]) continue; path.add(nums[i]); backtracking(nums, i + 1); path.remove(path.size() - 1); } } }
|
代码随想录

使用used数组记录当前元素在树枝和树层上是否使用过
- used[i - 1] == true,说明同一树枝candidates[i - 1]使用过
- used[i - 1] == false,说明同一树层candidates[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 30 31 32 33 34 35
| class Solution { List<List<Integer>> result = new ArrayList<>(); LinkedList<Integer> path = new LinkedList<>(); boolean[] used; public List<List<Integer>> subsetsWithDup(int[] nums) { if (nums.length == 0){ result.add(path); return result; } Arrays.sort(nums); used = new boolean[nums.length]; subsetsWithDupHelper(nums, 0); return result; } private void subsetsWithDupHelper(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]){ continue; } path.add(nums[i]); used[i] = true; subsetsWithDupHelper(nums, i + 1); path.removeLast(); used[i] = false; } } }
|