当前位置:网站首页>LeetCode 39. 组合总和
LeetCode 39. 组合总和
2022-07-02 06:07:00 【大白羊_Aries】
题目描述
解法
这道题超级简单,如果你看过 LeetCode 77. 组合 这篇的解法,你肯定知道 backtrace 时 i i i 都是从 s t a r t start start 开始,那么下一层回溯树就是从 s t a r t + 1 start + 1 start+1 开始,从而保证 n u m s [ s t a r t ] nums[start] nums[start] 这个元素不会被重复使用
// 回溯算法标准框架
for (int i = start; i < nums.size(); i++) {
// ...
// 递归遍历下一层回溯树,注意参数
backtrack(nums, i + 1, target);
// ...
}
但是,我们现在希望能够重复使用 n u m s [ s t a r t ] nums[start] nums[start] 这个元素,那么很好办嘛,我只要把 i + 1 i + 1 i+1 改成 i i i 即可
// 回溯算法标准框架
for (int i = start; i < nums.size(); i++) {
// ...
// 递归遍历下一层回溯树
backtrack(nums, i, target);
// ...
}
下面是完整实现
class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
int trackSum;
vector<int> track;
backtrace(candidates, target, 0, track, trackSum);
return res;
}
void backtrace(vector<int>& candidates, int target, int start, vector<int>& track, int trackSum)
{
if (trackSum == target)
{
res.push_back(track);
return;
}
if (trackSum > target) return;
for (int i = start; i < candidates.size(); i++)
{
trackSum += candidates[i];
track.push_back(candidates[i]);
backtrace(candidates, target, i, track, trackSum);
track.pop_back();
trackSum -= candidates[i];
}
}
};
边栏推荐
猜你喜欢
Problems encountered in uni app development (continuous update)
MySQL transaction and isolation level
Google play academy team PK competition, official start!
I/o impressions from readers | prize collection winners list
Google Play Academy 组队 PK 赛,正式开赛!
Reading classic literature -- Suma++
如何使用MITMPROXy
Software testing Q & A
Comment utiliser mitmproxy
Step by step | help you easily submit Google play data security form
随机推荐
AttributeError: ‘str‘ object has no attribute ‘decode‘
ZABBIX server trap command injection vulnerability (cve-2017-2824)
Go 学习笔记整合
Can't the dist packaged by vite be opened directly in the browser
Use some common functions of hbuilderx
495. Timo attack
Some descriptions of Mipi protocol of LCD
Shenji Bailian 3.52-prim
Mock simulate the background return data with mockjs
Lambda 表达式 和 方法引用
【C语言】简单实现扫雷游戏
Current situation analysis of Devops and noops
Community theory | kotlin flow's principle and design philosophy
servlet的web.xml配置详解(3.0)
[C language] screening method for prime numbers
Zabbix Server trapper 命令注入漏洞 (CVE-2017-2824)
keepalived安装使用与快速入门
I/o impressions from readers | prize collection winners list
从设计交付到开发,轻松畅快高效率!
Software testing - concept