首页 > 其他 > 详细

Combination-Sum II

时间:2014-04-05 10:33:38      阅读:417      评论:0      收藏:0      [点我收藏+]

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]

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     vector<vector<int> > combinationSum2(vector<int> &num, int target) {
 4         sort(num.begin(), num.end());
 5         vector<vector<int> > res;
 6         vector<int> com;
 7         combinationSum2(num, target, res, com, 0);
 8         return res;
 9     }
10     
11     void combinationSum2(vector<int>& num, int target, vector<vector<int> > &res, vector<int> &com, int start)
12     {
13         if(target == 0) {
14             res.push_back(com);
15             return;
16         }
17         for(int i = start; i < num.size() && num[i] <= target; i++) {
18             if(i > start && num[i] == num[i-1]) continue;  // !duplicate cases
19             com.push_back(num[i]);
20             combinationSum2(num, target-num[i], res, com, i+1);
21             com.pop_back();
22         }
23     }
24 };
bubuko.com,布布扣

 

Combination-Sum II,布布扣,bubuko.com

Combination-Sum II

原文:http://www.cnblogs.com/zhengjiankang/p/3646360.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!