39. Combination Sum

题目链接
tag:

  • Medium;

question:
  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 1:

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

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[[2,2,2,2],
[2,3,3],
[3,5]]

思路:
  像这种结果要求返回所有符合要求解的题十有八九都是要利用到递归,而且解题的思路都大同小异,如果仔细研究这样题目发现都是一个套路,都是需要另写一个递归函数,这里我们新加入三个变量,start记录当前的递归到的下标,out为一个解,res保存所有已经得到的解,每次调用新的递归函数时,此时的target要减去当前数组的的数,具体看代码如下:

class Solution {
public:
    vector> combinationSum(vector& candidates, int target) {
        vector> res;
        combinationSumDFS(candidates, target, 0, {}, res);
        return res;
    }
    
    void combinationSumDFS(vector& candidates, int target, int start, vector out, vector>& res) {
        if (target < 0) return;
        if (target == 0) {res.push_back(out); return;}
        for (int i = start; i < candidates.size(); ++i) {
            out.push_back(candidates[i]);
            combinationSumDFS(candidates, target - candidates[i], i, out, res);
            out.pop_back();
        }
    }
};

你可能感兴趣的:(39. Combination Sum)