当前位置:网站首页>Leetcode39 combined sum
Leetcode39 combined sum
2022-04-23 02:01:00 【Xicheng Fengyu building】
LeetCode39- Combinatorial summation
One 、 Title Description
Two 、 Topic analysis
2.1 Backtracking tree
Combinatorial problem is a typical problem that needs to be solved by backtracking algorithm , When dealing with backtracking algorithms , Think about the structure of the backtracking tree , And try to draw the backtracking tree of the problem , When drawing the backtracking tree , Pay attention to a special requirement in the title :
There is no limit to the same number
, The following is an illustration of the backtracking tree ( With[2,3,6,7]
For example ):
2.2 Recursive termination condition
According to the title, it is easy to think of at least two termination conditions :
(1) The sum on the current traversal path is equal to target When , Then collect the results , And no recursion at the next level
(2) The sum on the current traversal path is greater than target When , Then this path can be pruned directly , No recursion at the next level
3、 ... and 、 Basic code implementation
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
solve(candidates, target, res, new ArrayList<>(), 0, 0);
return res;
}
// curRes Store the nodes in the current path
// curSum Store the sum of the current path node
// res Used to collect all sequences that meet the conditions
public void solve(int[] candidates, int target, List<List<Integer>> res,List<Integer> curRes, int startIndex, int curSum) {
if (curSum == target) {
res.add(new ArrayList<>(curRes));
return;
}
if (curSum > target) {
return;
}
for (int i = startIndex; i < candidates.length; i += 1) {
curSum += candidates[i];
curRes.add(candidates[i]);
solve(candidates, target, res, curRes, i, curSum);
curSum -= candidates[i];
curRes.remove(curRes.size() - 1);
}
}
}
Four 、 Further optimization
The two recursive termination conditions given above can only be regarded as the basic bound conditions of backtracking algorithm , Used to terminate recursion , But we don't give the pruning condition of backtracking algorithm ,curSum > target You can only cut the branches under the same path , You can't cut off branches on the same layer , In fact, in the process of backtracking ,
When we need to extend nodes of the same layer ( namely for In the cycle ), If the nodes of the same layer are extended in ascending order ( Just sort the original array in ascending order ), Then we can also prune
, The condition for pruning is stillcurSum > target
, The optimized code is as follows :
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
solve(candidates, target, res, new ArrayList<>(), 0, 0);
return res;
}
/** * Solve the combinatorial summation problem by backtracking algorithm * * @param candidates * @param target * @param res Store all results that meet the conditions * @param curRes Store the results that meet the conditions in the current search path * @param startIndex The index at the beginning of each layer */
public void solve(int[] candidates,
int target, List<List<Integer>> res,
List<Integer> curRes, int startIndex, int curSum) {
if (curSum == target) {
res.add(new ArrayList<>(curRes));
return;
}
if (curSum > target) {
// Only the branches under the same path can be cut here
return;
}
for (int i = startIndex; i < candidates.length; i += 1) {
curSum += candidates[i];
if (curSum > target) {
// Cut off the branches of the same layer , namely for The loop is no longer extended
break;
}
curRes.add(candidates[i]);
solve(candidates, target, res, curRes, i, curSum);
curSum -= candidates[i];
curRes.remove(curRes.size() - 1);
}
}
}
5、 ... and 、 Submit results
版权声明
本文为[Xicheng Fengyu building]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220844276829.html
边栏推荐
- Ziguang micro financial report is outstanding. What does the triple digit growth of net profit in 2021 depend on
- 校园转转二手市场源码
- English abbreviation of role personal attribute
- 2022.4.20-----leetcode.388
- 教程】如何用GCC“零汇编”白嫖MDK
- 42. Use k3det in mmrotate for rotating target detection, MNN deployment and ncnn deployment
- Introduction to micro build low code zero Foundation (lesson 2)
- leetcode:27. Remove element [count remove]
- 拨号vps会遇到什么问题?
- 我国科学家揭示突破水稻产量瓶颈新机制
猜你喜欢
Challenges often faced by client project management
一些使用代理IP的小技巧。
《维C中国》乡村助农暖人心第三站嘉宝果农场
leetcode:27. Remove element [count remove]
W801 / w800 / w806 unique ID / CPUID / flashid
How to change the size of SVG pictures without width in openlayer
Analyze the three functions of static proxy IP.
Micro build low code zero foundation introductory course
How to classify proxy IP?
简洁开源的一款导航网站源码
随机推荐
批处理多个文件合成一个HEX
About how to import C4d animation into lumion
JSP basic knowledge summary
用TensorFlow实现线性回归(包括过程中出现的问题及解决方法)
2022第六季完美童模 IPA國民賽領跑元宇宙賽道
《维C中国》乡村助农暖人心第三站嘉宝果农场
2022.4.22-----leetcode. three hundred and ninety-six
What are the common proxy IP problems?
mb_ substr()、mb_ Strpos() function (story)
Quel est le fichier makefile?
2022.4.20-----leetcode.388
89 logistic回归用户画像用户响应度预测
What is BGP server and what are its advantages?
K zeros after leetcode factorial function
Shardingsphere sub database and sub table
FL studio20. 8 the latest Chinese version installation and download graphic tutorial
Digital collection platform settled in digital collection platform to develop SaaS platform of digital collection
BGP服务器在什么业务场景会被用到?
Longest common subsequence (record path version)
Today will finally write system out. Println()