开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第23天,点击查看活动详情
前言
算法的重要性不言而喻!区分度高!
现在学习的门槛低了,只有能上网每个人都可以学编程!培训班6个月就可以培养出来能干活的人,你怎么从这些人中脱颖而出?没错!就是学算法,学一些底层和基础的东西。
说的功利点是为了竞争,卷死对手。真心话说就是能提高自己的基础能力,为技术可持续发展做好充分的准备!!!
提前入门学习书籍:CPrimerPlus、大话数据结构
刷题网站
我是按照代码随想录提供的刷题顺序进行刷题的,大家也可以去刷leetcode最热200道,都可以
刷题嘛,最重要的就是坚持了!!!
画图软件
OneNote
这个要经常用,遇见不懂的流程的话就拿它画一画!
笔记软件
Typoral
题目
今天力扣挂掉了,就拿代码随想录的代码来看下吧
解析
回溯三部曲
- 确定回溯的参数和返回值
参数还是看需要什么就写什么
- 二维数组收集最终结果
- 一维数组收集路径结果
- candidates是目标数组
- target是从目标数组中找到的结果
- sum是用来计算递归路径中节点的和
- idx为横向循环的索引
public void backtracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) {
- 确定回溯终止的条件
根据题意这里想要程序终止的条件应该是为递归得到节点的值sum大于目标值了
if (sum + candidates[i] > target) break;
- 回溯搜索的遍历过程
递归的时候我们要记录各节点值相加之和,然后去和目标值target去比较。
如果相等的话那就把这个路径加到最终的结果集res
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
之后还是回溯的模版代码
for (int i = idx; i < candidates.length; i++) {
// 如果 sum + candidates[i] > target 就终止遍历
if (sum + candidates[i] > target) break;
path.add(candidates[i]);
backtracking(res, path, candidates, target, sum + candidates[i], i);
path.remove(path.size() - 1); // 回溯,移除路径 path 最后一个元素
}
完整代码
这里把判断循环结束的条件放在了for循环里是因为只有开始计算结果的时候才能去比较符不符合,但只有在for循环里才做计算
// 剪枝优化
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates); // 先进行排序
backtracking(res, new ArrayList<>(), candidates, target, 0, 0);
return res;
}
public void backtracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) {
// 找到了数字和为 target 的组合
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = idx; i < candidates.length; i++) {
// 如果 sum + candidates[i] > target 就终止遍历
if (sum + candidates[i] > target) break;
path.add(candidates[i]);
backtracking(res, path, candidates, target, sum + candidates[i], i);
path.remove(path.size() - 1); // 回溯,移除路径 path 最后一个元素
}
}
}