Combination Sum II
2014-05-01 03:53
323 查看
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in Cwhere the candidate numbers
sums to T.
Each number in C may only be used once in the combination.
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
target
A solution set is:
class Solution {
public:
vector<vector<int> >res;
vector<vector<int> > combinationSum2(vector<int> &num, int target)
{
res.clear();
sort(num.begin(), num.end());
vector<int> path;
execute(num, target, 0, path);
return res;
}
void execute(vector<int> &num, int target, int pos, vector<int> &path)
{
for (int i = pos; i < num.size(); i++)
{
if( i > pos && num[i] == num[i - 1])
continue;
if (target < num[i])
return;
path.push_back(num[i]);
if (target == num[i])
{
res.push_back(path);
path.pop_back();
return;
}
execute(num, target - num[i], i + 1, path);
path.pop_back();
}
}
};
sums to T.
Each number in C may only be used once in the combination.
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
10,1,2,7,6,1,5and
target
8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
class Solution {
public:
vector<vector<int> >res;
vector<vector<int> > combinationSum2(vector<int> &num, int target)
{
res.clear();
sort(num.begin(), num.end());
vector<int> path;
execute(num, target, 0, path);
return res;
}
void execute(vector<int> &num, int target, int pos, vector<int> &path)
{
for (int i = pos; i < num.size(); i++)
{
if( i > pos && num[i] == num[i - 1])
continue;
if (target < num[i])
return;
path.push_back(num[i]);
if (target == num[i])
{
res.push_back(path);
path.pop_back();
return;
}
execute(num, target - num[i], i + 1, path);
path.pop_back();
}
}
};
相关文章推荐
- 一个电脑运行多个tomcat
- PHP十天快速入门等收集资料
- JTGHMJTT
- [hdu 1028] Ignatius and the Princess III (母函数)
- console.read()读入的内容
- Combination Sum
- 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