[Leetcode]Combination Sum
2015-10-12 21:37
519 查看
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
A solution set is:
class Solution {
public:
/*dfs
*/
void dfs(vector<vector<int>>&result,vector<int>&path,int start,vector<int>&vec,int n){
if(n==0){//one solution
result.push_back(path);
return;
}
for(int i = start;i < vec.size();i++){
if(vec[i] > n)continue;
path.push_back(vec[i]);
dfs(result,path,i,vec,n-vec[i]);
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>>result;
vector<int>path;
sort(candidates.begin(),candidates.end());
dfs(result,path,0,candidates,target);
return result;
}
};
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,7and target
7,
A solution set is:
[7]
[2, 2, 3]
class Solution {
public:
/*dfs
*/
void dfs(vector<vector<int>>&result,vector<int>&path,int start,vector<int>&vec,int n){
if(n==0){//one solution
result.push_back(path);
return;
}
for(int i = start;i < vec.size();i++){
if(vec[i] > n)continue;
path.push_back(vec[i]);
dfs(result,path,i,vec,n-vec[i]);
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>>result;
vector<int>path;
sort(candidates.begin(),candidates.end());
dfs(result,path,0,candidates,target);
return result;
}
};
相关文章推荐
- Android 自定义下拉刷新上拉加载更多Listview
- Java多线程21:多线程下的其他组件之CyclicBarrier、Callable、Future和FutureTask
- 【原创文章】有梦勇敢去追
- [ActionScript 3.0] AS3虚线绘制方法
- [计划任务 - dos]制作任务工具
- IDEA创建Maven项目
- 深入理解 Objective-C:方法缓存
- hdoj 2031 c++
- Javascript 数组查重
- 致独立手机游戏开发者的一封信
- 2015-10-12// 第一波只是为了试验一下。没有任何技术而言。。
- Android view手势缩放与移动
- C++ 现在一些人动不动就要挽起袖子自己写内存池,号称能提高性能,真当 Ulrich Drepper 是水货?
- 需要求三个长方体的体积,请编写一个基于对象的程序
- [Java] Java中带标签的break语句
- JavaScript原生秒表、计时器
- c++快捷键
- hdu5073Galaxy dp
- UVALive 7037 The Problem Needs 3D Arrays(最大密度子图)
- 利用Android studio快速搭建安卓开发环境