LintCode: Combination Sum II

C++

DFS

 1 class Solution {
 2 public:
 3     void help(vector<int> &a, int now, int sum, int target, vector<int> &path, vector<vector<int> > &ans, bool last) {
 4         if (sum > target) {
 5             return ;
 6         }
 7         if (now >= a.size()) {
 8             if (sum == target) {
 9                 ans.push_back(path);
10             }
11             return ;
12         }
13         if ((now == 0) || (a[now - 1] != a[now]) || last) {
14             path.push_back(a[now]);
15             help(a, now + 1, sum + a[now], target, path, ans, true);
16             path.pop_back();
17         }
18         help(a, now + 1, sum, target, path, ans, false);
19     }
20     /**
21      * @param num: Given the candidate numbers
22      * @param target: Given the target number
23      * @return: All the combinations that sum to target
24      */
25     vector<vector<int> > combinationSum2(vector<int> &num, int target) {
26         // write your code here
27         sort(num.begin(), num.end());
28         vector<int> path;
29         vector<vector<int> > ans;
30         help(num, 0, 0, target, path, ans, true);
31         return ans;
32     }
33 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值