java递归 对应LeetCode39 40题目
2021/10/17 14:39:28
本文主要是介绍java递归 对应LeetCode39 40题目,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
java递归 对应LeetCode39 40题目
- 排序 当数组之和大于target时候 跳出
- 递归中的判断条件(跳出递归的条件)
- 是否取当前数字(注意可以重复即取了之后 index不变,不取当前数字可以直接递归调用 index+1)
看代码:
class Solution { List<List<Integer>> res = new LinkedList<>(); public List<List<Integer>> combinationSum(int[] candidates, int target) { LinkedList<Integer> list = new LinkedList<>(); dfs(candidates, target, 0, res, list); return res; } private void dfs(int[] candidates, int target, int idx, List<List<Integer>> res, LinkedList<Integer> list) { if (target == 0) { res.add(new ArrayList<>(list)); return; } if (idx == candidates.length) { return; } // 跳过当前数字 dfs(candidates, target, idx + 1, res, list); // 选择当前数 if (target - candidates[idx] >= 0) { list.add(candidates[idx]); dfs(candidates, target - candidates[idx], idx, res, list); list.removeLast(); } } }
LeetCode40题:
**注意:**结果集不重复,数字不可重复使用,数组中有重复数字
- 对数组排序方便以后操作
- 计算数组中每个数字出现次数
- 写递归方法
- 跳出递归条件(target==0、index=length(遍历完了)、结果数组相加大于target)
- 递归操作:跳过当前数字(index+1);不跳过(判断可以添加几个当前数字,最后去掉添加上的元素)
这篇关于java递归 对应LeetCode39 40题目的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求