Combination Sum
2014-05-01 03:12
260 查看
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:
vector<vector<int> > res;
vector<vector<int> > combinationSum(vector<int> &candidates, int target)
{
res.clear();
vector<int> path;
sort(candidates.begin(), candidates.end());
execute(candidates, target, 0, path);
return res;
}
void execute(vector<int> &candidates, int target, int pos, vector<int>& path)
{
for (int i = pos; i < candidates.size(); i++)
{
if(candidates[i] > target)
return;
path.push_back(candidates[i]);
if(candidates[i] == target)
{
res.push_back(path);
path.pop_back();
return;
}
else
execute(candidates, target - candidates[i], i, path);
path.pop_back();
}
}
};
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:
vector<vector<int> > res;
vector<vector<int> > combinationSum(vector<int> &candidates, int target)
{
res.clear();
vector<int> path;
sort(candidates.begin(), candidates.end());
execute(candidates, target, 0, path);
return res;
}
void execute(vector<int> &candidates, int target, int pos, vector<int>& path)
{
for (int i = pos; i < candidates.size(); i++)
{
if(candidates[i] > target)
return;
path.push_back(candidates[i]);
if(candidates[i] == target)
{
res.push_back(path);
path.pop_back();
return;
}
else
execute(candidates, target - candidates[i], i, path);
path.pop_back();
}
}
};
相关文章推荐
- openfire build(2)
- 服务器结构探讨
- 谈如何把做事到位
- 配置WordPress运行环境 – Wampserver安装图解
- linux基础知识
- cvSeq的学习
- Careercup - Facebook面试题 - 5890898499993600
- oracle SQL优化实战经验
- 西邮Linux兴趣小组13级纳新免试题浅析(完结)
- ORACLE 异常处理
- S2SH整合Shiro之:java.lang.NoSuchMethodException: com.sun.proxy.$Proxy25
- 用hadoop实现SimRank++算法(1)----权值转移矩阵的计算
- 配置yii访问远程数据库
- Count and Say
- 【Java语法与C语言的区别】一
- Careercup - Facebook面试题 - 4922014007558144
- 实用Linux命令集锦
- 良好心态和行为决定于你对事业的选择
- 良好心态和行为决定于你对事业的选择
- Careercup - Facebook面试题 - 6139456847347712