[leetcode] Combination Sum

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]
 
 
 1 class Solution
 2 {
 3 public:
 4   void generateCombination(vector<vector<int> > &ret, const vector<int> &candidates, vector<int> &temp, int temp_target, int index)
 5   {
 6     for(int i=index; i<candidates.size(); i++)
 7     {
 8       if(temp_target == 0)
 9         ret.push_back(temp);
10 
11       if(candidates[i] <= temp_target)
12       {
13         temp.push_back(candidates[i]);
14         generateCombination(ret, candidates, temp, temp_target-candidates[i], i);
15         temp.pop_back();
16       }
17       else
18         return;
19     }
20   }
21   vector<vector<int> > combinationSum(vector<int> &candidates, int target)
22   {
23     vector<vector<int> > ret;
24     vector<int> temp;
25     sort(candidates.begin(), candidates.end());
26     generateCombination(ret, candidates, temp, target, 0);
27 
28     return ret;
29   }
30 };

 

posted @ 2015-03-16 10:36  imKirin  阅读(149)  评论(0编辑  收藏  举报