Combination Sum II
2015-08-14 16:17
246 查看
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:
void helper(vector<vector<int> > &svec, vector<int> &candidates, vector<int> &vec, int start, int sum, int target)
{
if(sum == target)
{
if(find(svec.begin(), svec.end(), vec) == svec.end())
svec.push_back(vec);
return;
}
for(int i = start; i < candidates.size(); ++ i)
{
if(sum + candidates[i] <= target)
{
vec.push_back(candidates[i]);
helper(svec, candidates, vec, i + 1, sum + candidates[i], target);
vec.pop_back();
}
}
}
vector<vector<int> > combinationSum2(vector<int>& candidates, int target)
{
vector<int> vec;
vector<vector<int> > svec;
int len = candidates.size();
if(len == 0)
{
return svec;
}
sort(candidates.begin(), candidates.end());
helper(svec, candidates, vec, 0, 0, target);
return svec;
}
};
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:
void helper(vector<vector<int> > &svec, vector<int> &candidates, vector<int> &vec, int start, int sum, int target)
{
if(sum == target)
{
if(find(svec.begin(), svec.end(), vec) == svec.end())
svec.push_back(vec);
return;
}
for(int i = start; i < candidates.size(); ++ i)
{
if(sum + candidates[i] <= target)
{
vec.push_back(candidates[i]);
helper(svec, candidates, vec, i + 1, sum + candidates[i], target);
vec.pop_back();
}
}
}
vector<vector<int> > combinationSum2(vector<int>& candidates, int target)
{
vector<int> vec;
vector<vector<int> > svec;
int len = candidates.size();
if(len == 0)
{
return svec;
}
sort(candidates.begin(), candidates.end());
helper(svec, candidates, vec, 0, 0, target);
return svec;
}
};
相关文章推荐
- Notification的一些简单的设置和简单的用法
- width:100%
- rsync安装部署
- SEAndroid的各种策略文件
- AC自动机算法
- Android Fragment 真正的完全解析(下)
- ICP算法与RANSAC算法描述
- POJ 1094-Sorting It All Out(拓扑排序)
- 设计模式之 工厂模式
- javaweb学习总结(十)——HttpServletRequest对象(一)
- SpringMVC Controller 介绍
- hdu 1848 博弈
- 网贷系统架构——前端框架的选择
- JS 对象(Object)和字符串(String)互转
- HDU 2222
- LayoutInflater作用及使用
- 根据已知的日期获取星期
- 图结构练习——最小生成树
- STM32的USART DMA传输(转)
- UIButton的发现