《LeetCode力扣练习》代码随想录——回溯算法(子集II—Java)
刷题思路来源于 代码随想录
90. 子集 II
-
回溯
class Solution { private List<Integer> path = new ArrayList<>(); private List<List<Integer>> result = new ArrayList<>(); private boolean[] used; public List<List<Integer>> subsetsWithDup(int[] nums) { used = new boolean[nums.length]; Arrays.sort(nums); backtrack(nums, 0); return result; } private void backtrack(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 - 1] == nums[i] && used[i - 1] == false) { continue; } path.add(nums[i]); used[i] = true; backtrack(nums, i + 1); path.remove(path.size() - 1); used[i] = false; } return; } }