数字组合 II
2015-08-27 01:01
363 查看
给出一组候选数字(C)和目标数字(T),找出C中所有的组合,使组合中数字的和为T。C中每个数字在每个组合中只能使用一次。
样例
给出一个例子,候选数字集合为[10,1,6,7,2,1,5] 和目标数字
8 ,
解集为:[[1,7],[1,2,5],[2,6],[1,1,6]]
注意
所有的数字(包括目标数字)均为正整数。
元素组合(a1, a2,
… , ak)必须是非降序(ie, a1 ≤ a2 ≤
… ≤ ak)。
解集不能包含重复的组合。
样例
给出一个例子,候选数字集合为[10,1,6,7,2,1,5] 和目标数字
8 ,
解集为:[[1,7],[1,2,5],[2,6],[1,1,6]]
注意
所有的数字(包括目标数字)均为正整数。
元素组合(a1, a2,
… , ak)必须是非降序(ie, a1 ≤ a2 ≤
… ≤ ak)。
解集不能包含重复的组合。
class Solution { public: /** * @param num: Given the candidate numbers * @param target: Given the target number * @return: All the combinations that sum to target */ vector<vector<int> > combinationSum2(vector<int> &num, int target) { // write your code here vector<vector<int> > result; int n = num.size(); if (n < 1) { return result; } set<vector<int> > temp; sort(num.begin(), num.end()); vector<int> buf; visit(num, target, 0, n, buf, temp); for (set<vector<int> >::iterator it = temp.begin(); it != temp.end(); it++) { result.push_back(*it); } return result; } private: void visit(vector<int> &num, int target, int pos, int n, vector<int> &buf, set<vector<int> > &temp) { if (pos >= n) { return; } if (num[pos] > target) { return; } buf.push_back(num[pos]); if (num[pos] == target) { temp.insert(buf); } else { visit(num, target-num[pos], pos+1, n, buf, temp); } buf.pop_back(); visit(num, target, pos+1, n, buf, temp); } };
相关文章推荐
- Android碎片化问题
- QGraphicsItem中子Item与父Item的消息传递问题
- 087 Scramble String [Leetcode]
- Ural 1780 Gray Code (暴力)
- R语言-找出向量或矩阵中的最大10个数
- front-end
- playframework 一步一步来 之get started
- c递归实现 汉诺塔
- VS2010下多线程的调试
- iOS部分-UI基础控件 - 01天 入门 第08课 创建应用程序中的一些细节
- Leetcode: Add Binary
- thinkinginjava学习笔记04_初始化与清理
- 有符号数据的表示
- JSF : Page Forward vs Page Redirect
- PWM输入模式捕捉4路PWM波形的周期和占空比讲解
- 表单提交:button input submit 的区别
- iOS部分-UI基础控件 - 01天 入门 第07课 私有扩展&IBAction
- 欢迎使用CSDN-markdown编辑器
- iOS部分-UI基础控件 - 01天 入门 第06课 gif的简单实用
- 驱动主要数据结构