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;
    }
};
相关推荐
徐小黑ACG3 分钟前
Golang 基础05 结构体struct
开发语言·算法·golang
码完就睡12 分钟前
数据结构——红黑树
数据结构
码爸21 分钟前
数据结构详细介绍
数据结构
Navigator_Z31 分钟前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
北极有牛1 小时前
cpp学习笔记--常量指针
java·开发语言·算法
GPU实战笔记1 小时前
云端 GPU 训练的账户余额提醒:它能说明什么,不能说明什么?
深度学习·算法·成本管理·gpu云计算·云端训练
半杯咖啡半行码1 小时前
C++ 编程与 STL 模板:从泛型编程到内存安全详解
开发语言·c++
浮链序1 小时前
怎么证明"你这个模型是偷我的"——把蒸馏变成取证工具
算法·安全·llm
小O的算法实验室1 小时前
IEEE TMC,面向异构物联网的多目标量子行为拓扑优化算法
算法
圣保罗的大教堂2 小时前
leetcode 301. 删除无效的括号 困难
leetcode