https://leetcode.cn/problems/subsets/
题目要求
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
回溯
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> list = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
backtrack(nums, 0);
return res;
}
public void backtrack(int[] nums, int startIndex) {
// if (startIndex >= nums.length) return;
res.add(new ArrayList<>(list));
for (int i = startIndex; i < nums.length; i++) {
list.add(nums[i]);
backtrack(nums, i + 1);
list.removeLast();
}
}
}
- 当起始位置大于数组的长度时递归结束;每一次递归的自己需要添加到结果子集中;
- 这里也可以不加递归条件,因为大于数组长度时for也已经结束