题目
https://leetcode-cn.com/problems/subsets/
更新:
class Solution {
ArrayList<List<Integer>> res=new ArrayList<>();
int[] nums;
public List<List<Integer>> subsets(int[] nums) {
this.nums=nums;
dfs(new ArrayList<Integer>(),0);// 暂时子集,选取开始位置
return res;
}
public void dfs(ArrayList<Integer> tmp,int start){
res.add(new ArrayList<>(tmp));//不管当前多长,都加入结果,由于下标的限制不会超过数组长度
for(int i=start;i<nums.length;i++){
tmp.add(nums[i]);
dfs(tmp,i+1);
tmp.remove(tmp.size()-1);
}
}
}
分析
算是官方题解的思路了:
遍历每一位数字,分为取和不取两种情况。
代码
class Solution {
ArrayList<List<Integer>> res;
ArrayList<Integer> list;
int[] nums;
public List<List<Integer>> subsets(int[] nums) {
this.nums=nums;
res=new ArrayList<>();
if(nums==null||nums.length==0)
return new ArrayList<>();
list=new ArrayList<>();
dfs(0);
return res;
}
public void dfs(int x){
if(x==nums.length){//遍历完了,从[0,len-1]都经历了取和不取
res.add(new ArrayList<>(list));
return;
}
//取这个元素
list.add(nums[x]);
dfs(x+1);
list.remove(list.size()-1);
//不取这个元素
dfs(x+1);
}
}