首页 > 其他 > 详细

LeetCode – Refresh – Combination Sum II

时间:2015-03-19 06:18:31      阅读:241      评论:0      收藏:0      [点我收藏+]

The different between I and II is that:

1. For II, each number only can be chosen ONCE.

2. The a number, in the array, encountered more than twice will cause result duplication. So either sort the array and skip the number if it same as the previous, or use find function check whether the result exists in the result vector or not.

For here, sort the input is better, since the output need to be in ascending order.

 

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

 

LeetCode – Refresh – Combination Sum II

原文:http://www.cnblogs.com/shuashuashua/p/4349269.html

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