回溯算法练习题 | 子集问题
LeetCode链接:78. 子集
1.题目描述
给你一个整数数组 nums
,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
示例 2:
1 2
| 输入:nums = [0] 输出:[[],[0]]
|
提示:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
nums
中的所有元素 互不相同
2.题解
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
| class Solution { List<List<Integer>> result = new ArrayList<>(); List<Integer> path = new ArrayList<>(); public List<List<Integer>> subsets(int[] nums) { backtracking(nums, 0); return result; }
public void backtracking(int[] nums, int start) { result.add(new ArrayList<>(path));
if (start >= nums.length) return;
for (int i = start; i < nums.length; i++) { path.add(nums[i]); backtracking(nums, i + 1); path.remove(path.size() - 1); } } }
|
1.题目描述
给你一个整数数组 nums
,其中可能包含重复元素,请你返回该数组所有可能的 子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
示例 1:
示例 2:
1 2
| 输入:nums = [0] 输出:[[],[0]]
|
提示:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
2.题解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { List<List<Integer>> result = new ArrayList<>(); List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) { Arrays.sort(nums); backtracking(nums, 0); return result; }
public void backtracking(int[] nums, int start) { result.add(new ArrayList<>(path)); if (start == nums.length) return; for (int i = start; i < nums.length; i++) { if (i > start && nums[i] == nums[i - 1]) continue; path.add(nums[i]); backtracking(nums, i + 1); path.remove(path.size() - 1); } } }
|