[Leetcode] 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] 

 

DFS!

 1 class Solution {
 2 public:
 3     void findNext(vector<vector<int> > &res, vector<int> &candidates, vector<int> v, int sum, int target, int idx) {
 4         if (sum > target || idx >= candidates.size()) {
 5             return;
 6         }
 7         if (sum == target) {
 8             res.push_back(v);
 9             return;
10         }
11         v.push_back(candidates[idx]);
12         findNext(res, candidates, v, sum + candidates[idx], target, idx);
13         v.pop_back();
14         findNext(res, candidates, v, sum, target, idx + 1);
15     }
16     
17     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
18         vector<vector<int> > res;
19         sort(candidates.begin(), candidates.end());
20         vector<int> v;
21         findNext(res, candidates, v, 0, target, 0);
22         return res;
23     }
24 };

 

posted @ 2014-04-02 21:29  Eason Liu  阅读(128)  评论(0编辑  收藏  举报