Combination Sum II
2015-06-08 21:03
393 查看
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where
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
A solution set is:
class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
sort(num.begin(), num.end());
vector<vector<int> > ret;
vector<int> cur;
Helper(ret, cur, num, target, 0);
return ret;
}
void Helper(vector<vector<int> > &ret, vector<int> cur, vector<int> &num, int target, int position)
{
if(target == 0)
ret.push_back(cur);
else
{
for(int i = position; i < num.size() && num[i] <= target; i ++)
{
if(i != position && num[i] == num[i-1])
continue;
cur.push_back(num[i]);
Helper(ret, cur, num, target-num[i], i+1);
cur.pop_back();
}
}
}
};
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
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> > combinationSum2(vector<int> &num, int target) {
sort(num.begin(), num.end());
vector<vector<int> > ret;
vector<int> cur;
Helper(ret, cur, num, target, 0);
return ret;
}
void Helper(vector<vector<int> > &ret, vector<int> cur, vector<int> &num, int target, int position)
{
if(target == 0)
ret.push_back(cur);
else
{
for(int i = position; i < num.size() && num[i] <= target; i ++)
{
if(i != position && num[i] == num[i-1])
continue;
cur.push_back(num[i]);
Helper(ret, cur, num, target-num[i], i+1);
cur.pop_back();
}
}
}
};
相关文章推荐
- C#中static void Main(string[ ] args)中的作用及解释
- How do I use Tasker to run a sync in FolderSync?
- 两个视图交互,bitmap绘制重叠时重影问题
- SQL Server ISNULL函数和Coalesce函数替换空值的区别
- Android-TextView
- 实例分析Java Class的文件结构
- (五)NS3中示例:网桥模块示例csma-bridge.cc程序的注释
- VS1838B 红外接收头接线及单片机编码原理
- dataGrid 编辑 更新 删除 取消
- 39. Combination Sum
- SOJ.Subtraction
- vs2010 中无法用qt设计师打开ui文件
- Hadoop RPC远程过程调用源码解析及实例
- bzoj-1085 骑士精神
- C# dev开发过程中的山炮问题汇总
- Java的native方法
- java打印前100个回文素数
- AlertDialog点击button时由于逻辑需要不关闭dialog的实现
- 使用Retrace还原被ProGuard混淆后的崩溃堆栈
- 第13周-项目1-小玩文件-用键盘输入文件名,统计输出文件中每个字母、数字字符出现的次数