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;
    }
};
相关推荐
wabs6663 小时前
关于贪心算法的思考
算法·贪心算法
社交怪人4 小时前
【判断大小】信息学奥赛一本通C语言解法(题号1043)
算法
Snasph4 小时前
GNU Make 用户手册(中文版)
服务器·算法·gnu
江澎涌4 小时前
拆解与 AI 的一次对话
人工智能·算法·程序员
sheeta19985 小时前
LeetCode 每日一题笔记 日期:2026.06.02 题目:3635. 最早完成陆地和水上游乐设施的时间 II
笔记·算法·leetcode
Lsk_Smion5 小时前
力扣实训 _ [102].层序遍历--前序--后续_递归与非递归的实现
数据结构·算法·leetcode
Lsk_Smion6 小时前
力扣实训 _ [25].K个一组链表
数据结构·链表
小欣加油6 小时前
leetcode3751 范围内总波动值I
java·数据结构·c++·算法·leetcode
代码中介商7 小时前
C++左值与右值:核心判断法则详解
开发语言·c++
玖玥拾7 小时前
C/C++ 基础笔记(七)
c语言·c++