从零开始的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;       
}
};
相关推荐
2401_841495648 分钟前
【数据结构】最短路径的求解
数据结构·动态规划·贪心·ipython·最短路径·迪杰斯特拉算法·弗洛伊德算法
西安同步高经理9 分钟前
秒表实现自动化测量助力时频测量行业发展、秒表检定仪、毫秒表测量仪
人工智能·算法
夏幻灵14 分钟前
C++ 里 什么时候不用指针,而选择值拷贝/深拷贝 ?
开发语言·c++·算法
这猪好帅16 分钟前
【算法】动态规划 - 数字三角形模型
算法·动态规划
yong999019 分钟前
基于小波分析与粒子群算法的电网潮流优化实现(MATLAB)
开发语言·算法·matlab
tgethe21 分钟前
Java 数组(Array)笔记:从语法到 JVM 内核
java·数据结构
Christo325 分钟前
2024《Three-way clustering: Foundations, survey and challenges》
人工智能·算法·机器学习·数据挖掘
艾醒32 分钟前
大模型原理剖析——解耦RoPE(旋转位置编码)的基本原理
算法
@淡 定35 分钟前
JVM内存区域划分详解
java·jvm·算法
客梦44 分钟前
数据结构-单链表
数据结构