随笔 - 112  文章 - 0  评论 - 0  阅读 - 1384

组合总和(回溯)

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

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

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

 

示例 1:

[2,3,6,7]
7

示例 2:

输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

输入: candidates = [2], target = 1
输出: []

复制代码
class Solution {
public:
    // 存储所有可能组合的结果集
    vector<vector<int>> res;
    // 临时存储当前递归路径下的组合
    vector<int> temp;

    // 回溯函数,用于生成所有和为target的组合
    // candidates: 可选的数字列表
    // target: 目标和
    // start: 当前搜索开始的索引位置
    void backtrack(vector<int>& candidates, int target, int start) {
        // 如果目标和为0,说明找到了一组符合条件的组合
        if (target == 0) {
            // 将当前组合加入结果集中
            res.push_back(temp);
            return;
        }
        // 如果目标和小于0,说明当前组合已不符合条件,直接返回
        if (target < 0) {
            return;
        }

        // 遍历从start到candidates末尾的所有元素
        for (int i = start; i < candidates.size(); i++) {
            // 将当前元素加入当前组合中
            temp.push_back(candidates[i]);
            // 递归调用,继续寻找剩余部分的组合,允许重复使用当前元素
            backtrack(candidates, target - candidates[i], i);
            // 回溯:撤销上一步的选择,尝试其他可能性
            temp.pop_back();
        }
    }

    // 主函数,返回所有和为target的不同组合
    // candidates: 可选的数字列表
    // target: 目标和
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        // 调用回溯函数开始搜索
        backtrack(candidates, target, 0);
        // 返回最终找到的所有组合
        return res;
    }
};
复制代码

 

posted on   _月生  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示