40和的组合第二弹
来源:互联网 发布:sql语言怎么查询数据 编辑:程序博客网 时间:2024/05/20 20:45
Combination Sum II
问题描述:
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.
The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6]]
测试代码:
class Solution { void find_answer(vector<int> candidates,vector<vector<int> >& solutions,vector<int>& solution,int target,int begin) { if (!target) { solutions.push_back(solution); return; } for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i) if (i == begin || candidates[i] != candidates[i - 1]) { solution.push_back(candidates[i]); find_answer(candidates,solutions, solution, target - candidates[i], i + 1); solution.pop_back(); } }public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int> > solutions; vector<int> solution; sort(candidates.begin(),candidates.end()); find_answer(candidates,solutions,solution,target,0); return solutions; }};
性能:
参考答案:
class Solution {public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); vector<vector<int>> res; vector<int> path; helper(candidates, 0, target, res, path); return res; }private: void helper(vector<int>& candidates, int pos , int target, vector<vector<int>>& res, vector<int>& path) { if (target == 0) { res.push_back(path); return; } if (pos >= candidates.size() || candidates[pos] > target) { return; } int count = 1; while (pos + count < candidates.size() && candidates[pos] == candidates[pos + count]) { count++; } for (int i = 1; i <= count; i++) { path.push_back(candidates[pos]); helper(candidates, pos + count, target - i * candidates[pos], res, path); } for (int i = 1; i <= count; i++) { path.pop_back(); } helper(candidates, pos + count, target, res, path); return; }};
性能:
阅读全文
0 0
- 40和的组合第二弹
- Objective - C基础: 第二天 - 10.继承的使用场合和组合使用
- [LeetCode]40 和的组合 II
- 解和的组合
- 39.和的组合
- 组合数的和
- Spring第二篇和第三篇的补充【JavaConfig配置、c名称空间、装载集合、JavaConfig与XML组合】
- 第二人生的源码分析(十九)人物组合显示
- 第二十五题 求取字符串的排练组合输出
- ObjC第二节:属性声明、类的组合
- 编译和解释的组合
- 聚合和组合的区别
- 聚合和组合的区别
- 聚合和组合的区别
- 继承和组合的比较
- 继承和组合的比较
- 聚合和组合的区别
- 字符串的排列和组合
- 在html中常用哪几种方式定义css
- 动态添加线程,然后监控多个线程是否都完成了
- 关于mathematica中添加注释的一些方法
- Java面向对象的三大特性之--《继承》
- 杭电3065(HDU3065)
- 40和的组合第二弹
- RecyclerView的安装包和source
- 函数
- POJ 1321 棋盘问题
- Bean的属性注入——为不同类型属性注值
- BZOJ 1797: [Ahoi2009]Mincut 最小割 图的联通 最小割 tarjan
- springboot + mybatis 多数据源最简解决方案
- 思维导图:一张图了解jQuery
- 个人理解tensor或多维数组的最佳方式