`

Combination Sum(c++实现)

 
阅读更多

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.
  • Elements in a combination (a1a2, � , ak) must be in non-descending order. (ie, a1 ? a2 ? � ? ak).
  • 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] 

 

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

 

欢迎关注微信公众号——计算机视觉:

 

0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics