题目
78
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
提示:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
nums 中的所有元素 互不相同
题解
输入的视角
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
private List<Integer> path = new ArrayList<>();
private int[] nums;
public List<List<Integer>> subsets(int[] nums) {
this.nums = nums;
dfs(0);
return ans;
}
/*输入视角 也就是先选 8种情况
n 1
n 2 n 2
n 3 n 3 n 3 n 3
*/
private void dfs(int i) {
if (i == nums.length) {
ans.add(new ArrayList<>(path));
return;
}
//不选元素
dfs(i+1);
//选择元素
path.add(nums[i]);
dfs(i+1);
//归零 遍历到底部可能会有其他子树没有遍历到,需要退回到与回溯前一样
path.remove(path.size() - 1);
}
}
答案的视角
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
private List<Integer> path = new ArrayList<>();
private int[] nums;
public List<List<Integer>> subsets(int[] nums) {
this.nums = nums;
dfs(0);
return ans;
}
/*答案的视角 也就是先是null往里面添加答案
n
1 2 3
2 3 3
3
*/
private void dfs(int i) {
//每次递归都要更新一次答案
ans.add(new ArrayList<>(path));
if (i == nums.length) {
return;
}
//为了避免重复 保证第i+1层的数大于第i层
for (int j = i; j < nums.length; j++) {
path.add(nums[j]);
dfs(j+1);
path.remove(path.size() - 1);
}
}
}