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     void search(vector<vector<int> > &result, vector<int> &tmp, vector<int> &candidates, int index, int target){
 2         int n = candidates.size();
 3         if(index >= n)
 4             return;
 5         while(index+1 < n && candidates[index] == candidates[index+1]){
 6             index++;
 7         }
 8         if(target == 0){
 9             result.push_back(tmp);
10             return;
11         }
12         if(target < candidates[index])
13             return;
14         search(result, tmp, candidates, index+1, target);
15         tmp.push_back(candidates[index]);
16         search(result, tmp, candidates, index, target-candidates[index]);
17         tmp.erase(tmp.end()-1);
18     }
19     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
20         // Start typing your C/C++ solution below
21         // DO NOT write int main() function
22         vector<vector<int> > result;
23         vector<int> tmp;
24         sort(candidates.begin(), candidates.end());
25         search(result, tmp, candidates, 0, target);
26         return result;
27     }

 

posted on 2013-10-16 21:58  waruzhi  阅读(193)  评论(0编辑  收藏  举报

导航