当前位置:网站首页>LeetCode 39. Combined sum
LeetCode 39. Combined sum
2022-07-02 06:10:00 【Great white sheep_ Aries】
Title Description
solution
This problem is super simple , If you've seen it LeetCode 77. Combine The solution of this article , You must know backtrace when i i i from s t a r t start start Start , So the next level of backtracking tree is from s t a r t + 1 start + 1 start+1 Start , To ensure that n u m s [ s t a r t ] nums[start] nums[start] This element will not be reused
// Standard framework of backtracking algorithm
for (int i = start; i < nums.size(); i++) {
// ...
// Recursively traverse the next level of backtracking tree , Pay attention to the parameters
backtrack(nums, i + 1, target);
// ...
}
however , Now we hope to reuse n u m s [ s t a r t ] nums[start] nums[start] This element , Then it's easy to do , I just want to i + 1 i + 1 i+1 Change to i i i that will do
// Standard framework of backtracking algorithm
for (int i = start; i < nums.size(); i++) {
// ...
// Recursively traverse the next level of backtracking tree
backtrack(nums, i, target);
// ...
}
Here is the complete implementation
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];
}
}
};
边栏推荐
猜你喜欢
随机推荐
锐捷EBGP 配置案例
Leverage Google cloud infrastructure and landing area to build enterprise level cloud native excellent operation capability
ES6的详细注解
LeetCode 90. 子集 II
Database learning summary 5
Current situation analysis of Devops and noops
LeetCode 283. 移动零
神机百炼3.53-Kruskal
Redis Key-Value数据库 【秒杀】
【C语言】筛选法求素数
亚马逊aws数据湖工作之坑1
脑与认知神经科学Matlab Psytoolbox认知科学实验设计——实验设计四
LeetCode 39. 组合总和
servlet的web.xml配置详解(3.0)
Classic literature reading -- deformable Detr
Some experience of exercise and fitness
keepalived安装使用与快速入门
Stc8h8k Series Assembly and c51 Real combat - NIXIE TUBE displays ADC, Key Series port reply Key number and ADC value
复杂 json数据 js前台解析 详细步骤《案例:一》
Sumo tutorial Hello World