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

Subscribe to see which companies asked this question

 

用递归做该题显得复杂度很高, 但是我觉得没有什么更好的办法. 用递归最关键的是明确每一步所需要完成的操作, 这样写起来会比较容易.

 

 1 class Solution {
 2 public:
 3     void solve(int depth, int maxdepth, int target, vector<vector<int> >& result,vector<int>& candidates, vector<int>& ret)
 4     {
 5         for(int i=0;i<=target/candidates[depth];i++){
 6             if(target-i*candidates[depth]<0)break;
 7             ret[depth]=i;
 8 
 9             if(target-i*candidates[depth]==0){//完成目标,记录下来
10                 vector<int> tmp;
11                 tmp.clear();
12                 for(int i=0;i<=maxdepth;i++)
13                     for(int j=0;j<ret[i];j++){
14                         tmp.push_back(candidates[i]);
15                     }
16                 result.push_back(tmp);
17                 return;
18             }
19             
20             if(depth+1==maxdepth+1){//最后一个数字的处理
21                 continue;
22             }
23 
24             solve(depth+1,maxdepth,target-i*candidates[depth],result,candidates,ret);
25         }
26     }
27 
28     vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
29         vector<vector<int> > result;
30         sort(candidates.begin(),candidates.end());
31         vector<int> ret;
32         ret.resize(candidates.size()+1);
33         solve(0,candidates.size()-1,target,result,candidates,ret);
34 
35         return result;
36     }
37 };

 

posted @ 2016-10-12 16:58  gremount  阅读(135)  评论(0编辑  收藏  举报