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 <= candidatesi <= 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;
    }
};
相关推荐
我想走路带风1 小时前
各自缓冲及实现
c++
青 春 记 忆1 小时前
LeetCode 53. 最大子数组和|Python 解法详解
python·算法·leetcode
豆瓣鸡2 小时前
算法日记 - Day10
算法
戴西软件2 小时前
戴西CAxWorks.VPG车辆工程仿真软件技术解析(上)——安全仿真体系的自动化构建
运维·网络·数据库·人工智能·算法·安全·自动化
zander2582 小时前
4. 寻找两个正序数组的中位数:用分割点代替合并
数据结构·算法
Kisorge2 小时前
【电机控制器】 基于STSPIN32G4的FOC控制
stm32·嵌入式硬件·算法
阿米亚波2 小时前
【C/C++包管理器】vcpkg(by microsoft)
c语言·c++·git·vscode·microsoft·github·vcpkg
Elivs2 小时前
RMSNorm函数
人工智能·算法·机器学习
敲上瘾3 小时前
redis常用数据类型与操作方法
数据结构·数据库·redis·缓存
tudousisi2223 小时前
P4447 [AHOI2018初中组] 分组 题解复盘
算法