class Solution {
List<Integer> t = new ArrayList<Integer>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
public List<List<Integer>> subsets(int[] nums) {
dfs(0,nums);
return ans;
}
public void dfs(int cur, int[] nums){
if(cur == nums.length){
ans.add(new ArrayList<Integer>(t));
return;
}
t.add(nums[cur]); // t.add(nums[0])
System.out.print(cur);
dfs(cur+1, nums);
t.remove(t.size() - 1);
dfs(cur+1,nums);
}
}
leetcode 78. 子集 这方法怎么得到结果的啊,没看懂
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- qq_34370249 2021-10-14 17:18关注
递归调用,
解释一下dfs方法
参数 cur 当前便拎数组的下标,nums数组
if -》如果,cur和数组的长度一致,退出,(这是递归退出的条件,也就是说,当数组的长度== 0 或者 cur走到了数组的最后一位时,退出)
t.add -> 将下标为cur的元素,放在t中
dfs 重复 之前的步骤,(递归调用)
t.remove -> 移除t中的最后一个元素
dfs 重复之前的步骤,(递归调用)举个例子
数组[1,2,3],来说
第一次进入dfs方法时- cur = 0
0 != 3
t.add(1); // t = {1}
进入dfs方法- cur = 1
1 != 3
t.add(2)
进入dfs方法
重复以上步骤,就出来了cur = 2 3. 2 != 3 t.add(3) // t = {1,2,3} 进入dfs方法 4. 3 ==3 把这个t放入ans中, 此时 ans = {(1,2,3)} 退出,回到第三步 删除t中的最后一个元素 t.remove() // t = {1,2} 在进入dfs方法, 此时cur ==3 将{1,2}放入ans
- cur = 1
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 - cur = 0
悬赏问题
- ¥15 2020长安杯与连接网探
- ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
- ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
- ¥16 mybatis的代理对象无法通过@Autowired装填
- ¥15 可见光定位matlab仿真
- ¥15 arduino 四自由度机械臂
- ¥15 wordpress 产品图片 GIF 没法显示
- ¥15 求三国群英传pl国战时间的修改方法
- ¥15 matlab代码代写,需写出详细代码,代价私
- ¥15 ROS系统搭建请教(跨境电商用途)