码迷,mamicode.com
首页 > 其他好文 > 详细

(leetcode) Combination Sum

时间:2015-09-23 19:15:46      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

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 (a1, a2, … , 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 public:
 3     void backtrace(vector<int>& candidates,int sum,int target, vector<vector<int > > &results,vector<int> &result,int index)
 4     {
 5         if(sum == target) 
 6         {
 7             results.push_back(result);
 8             return;
 9         }
10         else if(sum > target)
11         {
12             return;
13         }
14         else if(sum < target)
15         {
16             for(int i = index; i < candidates.size();++i)
17             {
18                 result.push_back(candidates[i]);
19                 backtrace(candidates, sum + candidates[i],target,results,result,i);
20                 result.pop_back(); 
21             }
22         }
23         
24     }
25     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
26         sort(candidates.begin(),candidates.end());
27         vector<vector<int > > results;
28         vector<int> result;
29         int index = 0;
30         int sum = 0;
31         
32         backtrace(candidates,sum,target,results,result,index);
33 
34         return results;
35     }
36 };

 

(leetcode) Combination Sum

标签:

原文地址:http://www.cnblogs.com/chdxiaoming/p/4832804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!