题目:
两个方法本质就是决策树的画法不同
方法一解析:
代码:
javaclass Solution { private List<List<Integer>> ret;//返回结果 private List<Integer> path;//记录路径,注意返回现场 public List<List<Integer>> subsets(int[] nums) { path = new ArrayList<>(); ret = new ArrayList<>(); dfs(nums,0); return ret; } //i表示选择到了那一层 private void dfs(int[] nums, int indx){ //递归出口 if(indx == nums.length){ ret.add(new ArrayList<>(path)); return; } //选某个元素 path.add(nums[indx]); dfs(nums,indx+1); path.remove(path.size()-1);//回复现场 //不选某个元素 dfs(nums,indx+1); } }
方法二解析:
代码:
javaprivate List<List<Integer>> ret;//返回结果 private List<Integer> path;//记录路径 public List<List<Integer>> subsets(int[] nums) { path = new ArrayList<>(); ret = new ArrayList<>(); dfs(nums,0); return ret; } private void dfs(int[] nums, int pos){ ret.add(new ArrayList<>(path)); for(int i = pos; i < nums.length; i++){ path.add(nums[i]); //每一层只能往选过的元素,再往选 dfs(nums,i+1); path.remove(path.size()-1);//回复现场 } }
穷举vs暴搜vs深搜vs回溯vs剪枝专题一>子集
robin_suli2024-12-17 18:03
相关推荐
一去不复返的通信er4 小时前
力扣-图论-岛屿数量程序 代码狂人7 小时前
切片表与分区表的区别(数据开发面试版)HDU-Dade8 小时前
【校招笔试真题】简要介绍 Self-Attention 的前沿算法小郎君65810 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0邵奈一10 小时前
GPT-6.1 Terra速度是Sol的3倍,价格减半RaaS10010 小时前
Node.js Brotli RCE 漏洞自查指南:fetch、undici、axios 都在影响面,三分钟确认你的版本shehuiyuelaiyuehao11 小时前
算法56,重排链表qq_4523962311 小时前
第四篇:《索引原理与实战:B-tree、Hash、GIN、GiST、BRIN》西索斯coding12 小时前
Qwen3-Max 与 Qwen-Plus:60 个真实修复任务评测方案

