Wednesday, September 4, 2013

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] 
[0,1,0,2,1,0,1,3,2,1,2,1],
void generate(vector<int> v, int current_sum,  int target, int i,  vector<int> &candidates, vector<vector<int> > &results)
{
   if(current_sum == target)
   {
    results.push_back(v);
    return;
   }

   if(i >=  candidates.size() || current_sum > target)
    return;

   generate(v, current_sum, target, i+1, candidates, results);
   v.push_back(candidates[i]);
   generate(v, current_sum + candidates[i], target, i, candidates, results);
}

 vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
   vector<int> v;
   vector<vector<int> > results;
   sort(candidates.begin(), candidates.end());
   generate(v, 0, target, 0, candidates, results);
   return results;
} 

No comments:

Post a Comment