39. 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 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]
]


题目大意:

  给定一个整数集合candidates和一个整数target,找到candidates里元素相加之和等于target的组合,且组合唯一不可重复(组合元素可重复)。

解题思路:

  emmmmmmmmmmmmmmmmmmm~~~~~~~~~~~~~~~~,思路很简单,一个简单的递归回溯就行

解题代码:

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

    vector> combinationSum(vector& candidates, int target)
    {
        vector> res;
        vector combination;
        search(candidates, 0, combination, target, res);
        return res;
    }
};

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