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;
    }
};
相关推荐
不要葱花29 分钟前
接下来我将复现 10 篇强化学习算法:第 3 篇,一杯喜茶,搞定 Search-R1
算法·面试
geovindu42 分钟前
CSharp: Recursion Algorithm
开发语言·后端·算法·c#·递归算法
sTone873751 小时前
写时复制COW的第一性理解
android·c++·flutter
z小猫不吃鱼1 小时前
ResRep: Lossless CNN Pruning via Decoupling Remembering and Forgetting
算法·cnn·剪枝
卡提西亚1 小时前
leetcode-239. 滑动窗口最大值
算法·leetcode·职场和发展
CHANG_THE_WORLD1 小时前
逐层拆解:C++ 虚函数从对象内存到手工调用的完整过程
java·开发语言·c++
Scott9999HH1 小时前
2026 避坑实录:国产品牌压力变送器什么牌子好?从硬件抗扰到 C++ Qt 实时曲线绘制源码剖析
开发语言·c++·qt
ch0sen1pm1 小时前
800 行代码手写 Reactor 网络库:从 epoll 到聊天室
c++
ShallWeL1 小时前
【机器学习】(20)—— 类别不平衡
人工智能·算法·机器学习
明志数科1 小时前
具身智能数据标准化:从碎片化接口到统一工作组的技术路径
人工智能·算法·机器学习