LeetCode 40. Combination Sum II
2016-04-15 07:47
441 查看
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:
Almost the same idea as permutation, except that the pos value will have to keep heading forward.
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
10,1,2,7,6,1,5and target
8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Almost the same idea as permutation, except that the pos value will have to keep heading forward.
#include <vector> #include <iostream> #include <algorithm> using namespace std; void combinationSum(vector<int>& candidates, int pos, int& sum, int target, vector< vector<int> >& res, vector<int>& path) { if(sum > target) return; if(sum == target) { res.push_back(path); } for(int i = pos; i < candidates.size(); ++i) { if((i > pos && candidates[i] == candidates[i-1])) continue; // Draw a graph to show why this line is necessary. sum = sum + candidates[i]; path.push_back(candidates[i]); combinationSum(candidates, i + 1, sum, target, res, path); path.pop_back(); sum = sum - candidates[i]; } } // the inputs might have duplicates. // the output should be unique sequence. vector< vector<int> > combinationSum2(vector<int>& candidates, int target) { if(candidates.size() == 0) return {}; vector< vector<int> > res; vector<int> path; sort(candidates.begin(), candidates.end()); int sum = 0; combinationSum(candidates, 0, sum, target, res, path); return res; } int main(void) { vector<int> candidates{10, 1, 2, 7, 6, 1, 5}; vector< vector<int> > res = combinationSum2(candidates, 8); for(int i = 0; i < res.size(); ++i) { for(int j = 0; j < res[0].size(); ++j) { cout << res[i][j] << endl; } cout << endl; } }
相关文章推荐
- 面试记录二:腾讯后台研发
- 每日开源新闻速递(2016/4/15):Arch Linux 更新 4.5 内核
- Windows 10Bash命令
- HTML5表单_表单元素
- How do I use gcc, g++, and gdb?
- bzoj 2229: [Zjoi2011]最小割 分治&网络流
- 传澳洲电讯急寻汽车之家买家,接手财团有意私有化
- BZOJ 1003 物流运输 (动态规划 SPFA 最短路)
- nyoj 17 单调递增最长子序列
- HDU 2122 Ice_cream’s world III(最小生成树Kruskal)
- 极客班C++ STL(容器)第二周笔记
- HTML5表单_输入类型
- 2016年最值得新手程序员阅读的书:《增长工程师指南》
- 代码生成工具介绍和使用
- xshell无法链接ubuntu系统
- 设计模式之工厂模式
- 新安装Ubuntu Kylin 16.04系统,一个软件安装整理清单
- C#高级知识点&(ABP框架理论学习高级篇)——白金版
- nyoj 252 01串
- TransE论文第4节:实验