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 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40
cpp 复制代码
class Solution {
public:
    vector<vector<int>> res;
    vector<int>path;
    int sum = 0;
    void backtracking(vector<int>& candidates, int target,int startindex){
        if(sum > target) return;
        if(sum == target){
            res.push_back(path);
            return;
        }
        for(int i = startindex;i < candidates.size();i++){
            path.push_back(candidates[i]);
            sum += candidates[i];
            backtracking(candidates,target,i);//why i?
            //因为:题目允许加入重复元素。只有当回到上一层,才会变化
            path.pop_back();
            sum -= candidates[i];
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        //与组合|||问题 区别就是,可以重复选取一个数
        backtracking(candidates,target,0);
        return res;
    }
};
相关推荐
地平线开发者2 分钟前
大模型 | VLA 初识及在自动驾驶场景中的应用
算法·自动驾驶
py有趣4 分钟前
LeetCode学习之实现strStr()
学习·算法·leetcode
夏鹏今天学习了吗7 分钟前
【LeetCode热题100(52/100)】课程表
算法·leetcode·职场和发展
祁思妙想7 分钟前
【LeetCode100】--- 101.重排链表【思维导图+复习回顾】
算法·leetcode·链表
Dream it possible!20 分钟前
LeetCode 面试经典 150_链表_随机链表的复制(59_138_C++_中等)
c++·leetcode·链表
我是华为OD~HR~栗栗呀23 分钟前
华为od-22届考研-C++面经
java·前端·c++·python·华为od·华为·面试
文火冰糖的硅基工坊24 分钟前
[人工智能-大模型-69]:模型层技术 - 计算机处理问题的几大分支:数值型性问题、非数值型问题?
算法·决策树·机器学习
我是华为OD~HR~栗栗呀28 分钟前
华为OD, 测试面经
java·c++·python·华为od·华为·面试
OG one.Z1 小时前
05_逻辑回归
算法·机器学习·逻辑回归
lzptouch1 小时前
逻辑斯蒂回归(Logistic Regression)算法
算法·数据挖掘·回归