LeetCode39. Combination Sum

文章目录

一、题目

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the

frequency

of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Example 1:

Input: candidates = [2,3,6,7], target = 7

Output: [[2,2,3],[7]]

Explanation:

2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.

7 is a candidate, and 7 = 7.

These are the only two combinations.

Example 2:

Input: candidates = [2,3,5], target = 8

Output: [[2,2,2,2],[2,3,3],[3,5]]

Example 3:

Input: candidates = [2], target = 1

Output: []

Constraints:

1 <= candidates.length <= 30

2 <= candidates[i] <= 40

All elements of candidates are distinct.

1 <= target <= 40

二、题解

cpp 复制代码
class Solution {
public:
    vector<vector<int>> res;
    vector<int> tmp;
    void backtracking(vector<int>& candidates,int target,int sum,int startIndex){
        if(sum > target) return;
        if(sum == target){
            res.push_back(tmp);
            return;
        }
        for(int i = startIndex;i < candidates.size();i++){
            tmp.push_back(candidates[i]);
            sum += candidates[i];
            backtracking(candidates,target,sum,i);
            sum -= candidates[i];
            tmp.pop_back();
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        backtracking(candidates,target,0,0);
        return res;
    }
};
相关推荐
ChoSeitaku13 小时前
NO.14数据结构红黑树|树高|转化4阶B树|插入操作|删除操作
数据结构·b树
T1an-113 小时前
力扣70.爬楼梯
算法·leetcode·职场和发展
T1an-113 小时前
力扣169.多数元素
数据结构·算法·leetcode
进击中的小龙14 小时前
在vscode下的cmake项目里传参调试c++命令行程序
c++·vscode
violet-lz14 小时前
数据结构:七大线性数据结构从结构体定义到函数实现的的区别
数据结构
奔跑吧邓邓子16 小时前
【C++实战(74)】深入C++安全编程:密码学实战之旅
c++·安全·实战·密码学·安全编程
明天会有多晴朗16 小时前
C语言入门教程(第1讲):最通俗的C语言常见概念详解与实战讲解
c语言·开发语言·c++
Larry_Yanan16 小时前
QML学习笔记(二十四)QML的Keys附加属性
c++·笔记·qt·学习·ui
龙木之森17 小时前
纯 C++ 开发的 Telegram Bot 框架
c++·tui·telegram·bot
hqwest18 小时前
QT肝8天09--用户列表
开发语言·c++·qt·上位机·qt开发