码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Combination Sum II

时间:2015-03-19 06:18:55      阅读:135      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!