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

 

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
    void findSum(vector<int> &S,int sum,int level,int &t,vector<int> &buf,vector<vector<int>> &res){
        for(int i=level;i<S.size();i++){
            buf.push_back(S[i]);
            if(sum+S[i]==t)
                res.push_back(buf);
            if(sum+S[i]<=t)
                findSum(S,sum+S[i],i,t,buf,res);
            buf.pop_back();
        }
    }
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<int> buf;
        vector<vector<int>> res;
        sort(candidates.begin(),candidates.end());
        findSum(candidates,0,0,target,buf,res);
        return res;
    }
};

  

Combination Sum

上一篇:Servlet生命周期


下一篇:微信、QQ浏览器X5内核问题汇总