[leetcode -- backtracking] 39.Combination Sum

39. Combination Sum

题目: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

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

Note:

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

For example, given candidate set [2, 3, 6, 7] and target 7,

A solution set is:

[
  [7],
  [2, 2, 3]
]

Combination Sum

分析: 采用回溯法, 在每一次的递归中把剩下的元素分别加入到结果结合中, 并把target减去加入的数, 然后把剩下的元素放到下一层的递归中去解决. 代码在实现的过程中要注意重复元素的判断.

code:

class Solution {
public:
    vector> combinationSum(vector& candidates, int target) {
        vector> ret;
        vector tmp;
        helper(candidates, 0, target, tmp, ret);
        return ret;
    }
    
    void helper(vector& candidates, int begin, int target, vector& tmp, vector>& ret) {
        if(target < 0)
            return;
        
        if(target == 0)
            ret.push_back(tmp);
        
        for(int i = begin; i < candidates.size(); ++i) {
            if(i > 0 && candidates[i] == candidates[i-1])
                continue;
            tmp.push_back(candidates[i]);
            helper(candidates, i, target-candidates[i], tmp, ret);
            tmp.pop_back();
        }
    }
};

你可能感兴趣的:([leetcode -- backtracking] 39.Combination Sum)