LeetCode39 - Combination Sum

问题分析:

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

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> res;
    vector res_elem;
    
    vector> combinationSum(vector& 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 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;
            }
        }
    }
    
};

学习知识:

递归思想

 

 

 

 

你可能感兴趣的:(LeetCode,C++,LeetCode)