LeetCode – Refresh – Combination Sum II

本文介绍了一种解决组合求和问题的方法,特别关注如何通过排序和跳过重复数字来避免结果重复。使用C++实现了一个递归函数getComb,该函数通过检查每个元素是否与前一个元素相同来跳过重复项,并返回所有可能的组合。

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 };

 

转载于:https://www.cnblogs.com/shuashuashua/p/4349269.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值