Leetcode:Combination Sum II
来源:互联网 发布:pcb电路板设计软件 编辑:程序博客网 时间:2024/06/07 05:16
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 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 {public: vector<vector<int> > combinationSum2(vector<int> &num, int target) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<vector<int> > v_results; if(num.empty() ) return v_results; sort(num.begin(),num.end() ); vector<int> result; helper(num,0,target,result,v_results); return v_results; } void helper(vector<int>& candidates,int pos,int target,vector<int>& result,vector<vector<int> >& v_results) { if(target==0) { v_results.push_back(result); return; } if(target<0 || pos>=candidates.size() ) return; //qu result.push_back(candidates[pos]); helper(candidates,pos+1,target-candidates[pos],result,v_results); result.pop_back(); //not qu int tmp=pos; while(tmp<candidates.size()-1 && candidates[tmp]==candidates[tmp+1]) tmp++; helper(candidates,tmp+1,target,result,v_results); } };
需要注意去重,这是个多重背包问题。可以统计每个数字出现的个数,此题就转化成了Combination Sum
- LeetCode: Combination Sum II
- LeetCode: Combination Sum II
- [LeetCode]Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- [LeetCode] Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- LeetCode: Combination Sum II
- leetcode Combination Sum II
- [LeetCode]Combination Sum II
- [leetcode] Combination Sum II
- LeetCode-Combination Sum II
- LeetCode - Combination Sum II
- LeetCode:Combination Sum II
- 【Leetcode】Combination Sum II
- Combination Sum II 【leetcode】
- [LeetCode] Combination Sum II
- 创建任务需要大量的图形和设计和生产工作
- c# 自定义事件和委托
- 如何编写出高效的数据库连接池(附带完整代码C#和Java实现) .
- SqlCommandBuilder 的使用
- Android 读取<meta-data>元素的数据
- Leetcode:Combination Sum II
- 自悟
- SVM入门(一)至(三)Refresh
- rtsp协议总结
- How to write the better Makefile for cpputest
- This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery
- Android StagFright架构分析
- UITableView 的head 右边提示关键字母
- ListView和ScrollView 回到顶部