玛伊网站做兼职加入要多少钱,深圳竞价排名网络推广,抖音seo系统,河南论坛网站建设题目
78 给你一个整数数组 nums #xff0c;数组中的元素 互不相同 。返回该数组所有可能的子集#xff08;幂集#xff09;。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1#xff1a;
输入#xff1a;nums [1,2,3] 输出#xff1a;[[],[1],[2]…题目
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 ListListInteger ans new ArrayList();private ListInteger path new ArrayList();private int[] nums;public ListListInteger subsets(int[] nums) {this.nums nums;dfs(0);return ans;}/*输入视角 也就是先选 8种情况n 1n 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(i1);//选择元素path.add(nums[i]);dfs(i1);//归零 遍历到底部可能会有其他子树没有遍历到需要退回到与回溯前一样path.remove(path.size() - 1);}
}答案的视角
class Solution {private ListListInteger ans new ArrayList();private ListInteger path new ArrayList();private int[] nums;public ListListInteger subsets(int[] nums) {this.nums nums;dfs(0);return ans;}/*答案的视角 也就是先是null往里面添加答案n1 2 32 3 33 */private void dfs(int i) {//每次递归都要更新一次答案ans.add(new ArrayList(path));if (i nums.length) {return;}//为了避免重复 保证第i1层的数大于第i层for (int j i; j nums.length; j) {path.add(nums[j]);dfs(j1);path.remove(path.size() - 1);}}
}