题目:
解析:
决策树:
代码设计:
代码:
写法一:path为全局变量
javaprivate int ret,path,aim; public int findTargetSumWays(int[] nums, int target) { aim = target; dfs(nums,0); return ret; } private void dfs(int[] nums, int pos){ if(pos == nums.length){ if(path == aim) ret++; return; } //添加 '+' path += nums[pos]; dfs(nums,pos+1); path -= nums[pos];//回溯 //添加 '-' path -= nums[pos]; dfs(nums,pos+1); path += nums[pos];//回溯 }
写法二:path作为参数
javaprivate int ret,aim; public int findTargetSumWays(int[] nums, int target) { aim = target; dfs(nums,0,0); return ret; } private void dfs(int[] nums, int pos,int path){ if(pos == nums.length){ if(path == aim) ret++; return; } //添加 '+' dfs(nums, pos+1, path + nums[pos]); //添加 '-' dfs(nums, pos+1, path - nums[pos]); }
穷举vs暴搜vs深搜vs回溯vs剪枝系列一>
robin_suli2025-01-03 23:37
相关推荐
☼←安于亥时→❦1 小时前
PyTorch之张量创建与运算子豪-中国机器人1 小时前
枚举算法和排序算法能力测试qiuyunoqy1 小时前
基础算法之二分算法 --- 2爱干饭的boy1 小时前
手写Spring底层机制的实现【初始化IOC容器+依赖注入+BeanPostProcesson机制+AOP】二哈不在线2 小时前
代码随想录二刷之“动态规划”~GOcellurw2 小时前
俄罗斯方块终端游戏实现 —— C语言系统编程与终端控制诸葛务农3 小时前
光电对抗:多模/复合制导中算法和软件平台Swift社区3 小时前
LeetCode 378 - 有序矩阵中第 K 小的元素墨染点香3 小时前
LeetCode 刷题【73. 矩阵置零】