LeetCode39 - Combination Sum

本文介绍了一种使用递归方法解决组合总和问题的方法。对于一组无重复的候选数字,找出所有可能的组合,使得这些组合的元素之和等于目标数值。文章通过实例详细解释了递归过程,并提供了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题分析:

此问题同之前括号匹配问题一样,使用递归思想

Given a set of candidate numbers (candidates(without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example :

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

运用递归思想,重复利用一个数字的并代入求和,直到它的和达到target 或者它超过了target, 然后在递归返回,继续找下一个数字。

根据官网示例,[2, 3, 6, 7] 找寻 targey = 7 的组合:

递归开始:

push 2                 [2]                            sum = 2

push 2                 [2, 2]                        sum = 4

push 2                 [2, 2, 2]                    sum = 6

push 2                 [2, 2, 2, 2]                sum = 8 

sum = 8 > 7          递归返回     [2, 2, 2, 2]      pop 2         [2, 2, 2]

由于[2, 2, 2, 2]的sum > target,且原数组有序的,则下一次为[2, 2, 2, ?]必大于target,

即设置一个flag,用于高效递归:

sum = 8 > 7        flag = false        递归返回        [2, 2, 2, 2]      pop 2         [2, 2, 2]            flag == false         break --> [2, 2]

push 3                 [2, 2, 3]                    sum = 7

sum = 7 = 7        flag = false        递归返回        [2, 2, 3]          pop 3          [2, 2]                flag == false         break --> [2]

...

...

...

...

代码如下: 

class Solution {
public:
    vector<vector<int>> res;
    vector<int> res_elem;
    
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        if (candidates.size() == 0)     return res;
        addvectorres (0, 0, target, candidates);
        return res;
    }
    
    void addvectorres (int start, int sum, int target, vector<int> candidates)
    {
        bool flag;
        if (sum == target)
        {
            res.push_back(res_elem);
            flag = false;
            return;
        }
        else if (sum > target)  
        {
            flag = false;
            return;
        }
        else
        {
            for (int i = start; i < candidates.size(); i++)
            {
                res_elem.push_back(candidates[i]);
                addvectorres (i, sum + candidates[i], target, candidates);
                res_elem.pop_back();
                if (flag = false)   break;
            }
        }
    }
    
};

学习知识:

递归思想

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值