题目链接
子集
题目描述
注意点
- nums 中的所有元素 互不相同
- 解集 不能 包含重复的子集
- 可以按 任意顺序 返回解集
解答思路
代码
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
int depth = 0, idx = 0;
List<Integer> sonRes = new ArrayList<>();
res.add(sonRes);
dfs(nums, res, sonRes, depth, idx);
return res;
}
public void dfs(int[] nums, List<List<Integer>> res, List<Integer> sonRes, int depth, int idx) {
if (depth > nums.length) {
return;
}
for (int i = idx; i < nums.length; i++) {
sonRes.add(nums[i]);
res.add(new ArrayList<>(sonRes));
dfs(nums, res, sonRes, depth + 1, i + 1);
sonRes.remove(sonRes.size() - 1);
}
}
}
关键点