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

【leetcode】Combination Sum

时间:2015-05-15 13:20:00      阅读:99      评论: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 com(vector<int> &candidates,int start,int sum,int target,vector<int> &path,vector<vector<int> > &res)
 4     {
 5         if(sum>target)
 6             return ;
 7         if(sum==target)
 8         {
 9             res.push_back(path);
10             return ;
11         }
12 
13         int len=candidates.size();
14         for(int i=start;i<len;i++)
15         {
16             path.push_back(candidates[i]);
17             com(candidates,i,sum+candidates[i],target,path,res);
18             path.pop_back();
19         }
20     }
21 
22     vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
23         sort(candidates.begin(),candidates.end());
24         vector<vector<int> > res;
25         vector<int> path;
26         com(candidates,0,0,target,path,res);
27         return res;
28     }
29 };

 

【leetcode】Combination Sum

标签:

原文地址:http://www.cnblogs.com/jawiezhu/p/4505545.html

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