Combination Sum II
2015-07-25 19:06
337 查看
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
target
A solution set is:
本题为了避免超时,采用了上面博客的第二种算法,代码如下:
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]
解题思路:
和combination sum i相似的计算,不过candidates中的元素不能重复使用,并且我们将向量加入子集时还要考虑此向量是否已经存在。combination 1参考博客 http://blog.csdn.net/sinat_24520925/article/details/47058935本题为了避免超时,采用了上面博客的第二种算法,代码如下:
class Solution { public: vector<vector<int>> res; vector<int> pre; void cm(vector<int>& p, int tag,int l) { if(l==pre.size()) return; int temp=accumulate(p.begin() , p.end() , 0); if(temp==tag) { sort(p.begin(),p.end()); int flag=0; for(int j=0;j<res.size();j++) { if(res[j].size()==p.size()) { int t; for(t=0;t<p.size();t++) { if(res[j][t]!=p[t]) { break; } } if(t==p.size()) { flag=1;//已有相同的并加入到了res } } } if(flag==0) res.push_back(p); return ; } else if(temp>tag) return; else { for(int i=l+1;i!=pre.size();i++) { p.push_back(pre[i]); cm(p,tag,i); p.pop_back(); } } } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { if(candidates.size()==0) return res; if(target<=0) return res; int len=candidates.size(); sort(candidates.begin(),candidates.end()); pre=candidates; vector<int> tmp; cm(tmp,target,-1); return res; } };
相关文章推荐
- 【javaweb】Session原理以及浏览器禁止Cookie之后服务器如何获取Session
- Raid1源代码分析--写流程
- mysql数据库中如何修改已建好的表中的【列名】【列的属性】
- MFC子窗口向父窗口发送消息
- 最短路之Dijkstra算法
- 用xib自定义UITableViewCell的注意事项——重用问题
- ECharts学习总结(二):标签式单文件引入echarts的方法
- Python项目7:自定义公告板
- IOS实现在后台执行一定时间的任务
- c#中的程序集
- poj1007
- 基于Linux的智能家居的设计(4)
- Linux引导:历史和未来
- Hdu 4916 Count on the path
- ZOJ 3822 可能性DP
- MYSQL---%
- nfs基本应用之httpd+nfs负载均衡实验
- 数据库学习笔记——数据库连接池的工作原理
- C++之static
- #include "atlImage.h" 无法编译CImage img;