从零开始的CPP(33)多种终止条件的回溯

leetcode39

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

复制代码
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

这道题要使用回溯来解决,之前说过,回溯只需要搞清楚终止条件(防止一直递归下去)和递推条件就行。

回溯本质是深度优先搜索,可以看图来解释。先达到最大深度,再把2 3 6 7 都试一遍。不符合要求(sum>target)就弹栈(temp.pop_back),符合要求(sum=target)就把temp存入res再弹栈。为了防止重复搜索,设置一个k,保证只搜索索引>=当前索引的,不会搜索之前搜索过的

cpp 复制代码
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    vector<vector<int>> res = {};
    vector<int> temp = {};
    int sum = 0;
    int k = 0;
    helper(k,candidates, candidates[0], sum, temp, target, res);   
    return res;   
}
void helper(int k, vector<int>& candidates, int candidate, int& sum, vector<int>& temp, int target, vector<vector<int>>& res) {
    if (sum == target) {
        res.push_back(temp);
        sum = sum - temp[temp.size() - 1];
        temp.pop_back();
        return;
    }
    if (sum > target) {
        temp.pop_back();
        sum = sum- candidate;
        return;
    }
    for (int i = k; i < candidates.size(); i++) {
        temp.push_back(candidates[i]);
        sum = sum + candidates[i];
        helper(i,candidates, candidates[i],sum, temp, target, res);         
    }
    if (temp.empty()) return;        
        sum = sum - temp[temp.size() - 1];
        temp.pop_back();
        return;       
}
};
相关推荐
牧羊人.3332 小时前
动手学深度学习 07|Resnet网络与迁移学习
网络·人工智能·深度学习·神经网络·算法·cnn·迁移学习
All for pursuit.3 小时前
【并查集-2】399.除法求值
数据结构·c++·算法·leetcode
迪丽热爱3 小时前
一、C语言概述与程序结构
c语言·开发语言·算法
码爸3 小时前
动态规划介绍
算法·动态规划
怪奇云呼军4 小时前
教育试听预约后没到课,闪电智能 Voice Agent 如何做分层回访?
人工智能·python·算法·云计算·音视频
Nil2084 小时前
leetcode 416分割等和子集
算法·leetcode·职场和发展
云淡风轻~窗明几净4 小时前
角谷猜想的进展之三 移动了群山/沸騰的群山 2026-10-10
人工智能·算法·dubbo·图论
ForeverYang20154 小时前
一种无需训练缺陷数据生成算法--O2MAG
人工智能·深度学习·算法
xuxigifxfh5 小时前
牛客:HJ170 01序列
java·开发语言·算法·华为机考
朝朝辞暮i5 小时前
C++ 第 33 课:事件循环——spin() 到底在干什么
开发语言·c++·算法