LeetCode 39. 组合总和(回溯+剪枝)

题目:

链接:LeetCode 39. 组合总和

难度:中等

给你一个 无重复元素 的整数数组 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:

输入: candidates = 2,3,5, target = 8

输出: \[2,2,2,2,2,3,3,3,5]

示例 3:

输入: candidates = 2, target = 1

输出: \[\]

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidatesi <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40

回溯+剪枝:

详细解析看这篇回溯算法秒杀所有排列/组合/子集问题,这类题型通杀。

代码:

cpp 复制代码
class Solution {
public:
    vector<vector<int>> res;
    vector<int> track;
    int trackSum;
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        trackSum = 0;
        backtrack(candidates, 0, target);
        return res;
    }
    void backtrack(vector<int>& candidates, int start, int target) {
        if(trackSum == target) {
            res.emplace_back(track);
            return;
        }
        else if(trackSum > target) return;
        for(int i = start; i < candidates.size(); i++)
        {
            track.emplace_back(candidates[i]);
            trackSum += candidates[i];
            backtrack(candidates, i, target);  // 元素可复用,所以继续从第i位开始遍历
            track.pop_back();
            trackSum -= candidates[i];
        }
    }
};
相关推荐
余俊晖13 分钟前
多模态大模型细粒度视觉理解:Vision-OPD在线策略自蒸馏技术方案概述
人工智能·深度学习·算法·多模态·opd
胖大和尚24 分钟前
在C++的类中,是否可以把函数声明成__device__
c++·cuda
-dzk-25 分钟前
【链表】LC 160.相交链表
数据结构·链表
脚踏实地皮皮晨27 分钟前
003003001_Grid控件
开发语言·windows·算法·c#·visual studio
十年磨剑走天涯31 分钟前
C++ STL 容器操作复杂度速查表
开发语言·c++
Hi李耶39 分钟前
【LeetCode】6-Z字形变换
算法·leetcode·职场和发展
ziguo112240 分钟前
Windows API MessageBox 函数详解
c语言·c++·windows·visualstudio
王老师青少年编程44 分钟前
2023年CSP-J初赛真题及答案解析(11-15)
c++·真题·csp-j·答案·csp·初赛·信奥赛
15Moonlight1 小时前
C++进阶(09):特殊类设计
开发语言·c++
XiaoYu1__1 小时前
算法进阶·其一:用SCC、Tarjan算法与缩点思想解决有向图的连通关系及2-SAT问题的拓展
算法