力扣算法题—040组合求和二

 1 #include "000库函数.h"
 2 
 3 //第一感觉使用回溯比较快
 4 //96ms
 5 
 6 
 7 class Solution {
 8 public:
 9     vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
10         vector<vector<int>>R;
11         sort(candidates.begin(), candidates.end());
12         if (candidates.size() == 0)return R;
13         vector<int>v;//临时存放解    
14         Combin(candidates, R, v, target, 0, 0);        
15         return R;
16     }
17 
18     void Combin(vector<int>candidates, vector<vector<int>>&Res, vector<int>&v, int target, int start, int sum) {
19         if (sum == target) {
20             //sort(v.begin(), v.end());
21             Res.push_back(v);
22             return;
23         }
24         else if (sum > target)
25             return;
26 
27         for (int i = start; i < candidates.size(); ++i) {
28             if (i > start&&candidates[i] == candidates[i - 1])continue;//去除重复的组合            
29             v.push_back(candidates[i]);
30             Combin(candidates, Res, v, target, i + 1, sum + candidates[i]);//i+1是与上题的不同之处,不会出现重复使用元素
31             v.pop_back();//将数字退出                
32         }
33     }
34 
35 };
36 
37 void T040() {
38     vector<int> v;
39     vector<vector<int>>Res;
40     Solution s;
41     v = {10,1,2,7,6,1,5 };
42     Res = s.combinationSum2(v, 8);
43     for (auto &a : Res) {
44         for (auto b : a)
45             cout << b << "  ";
46         cout << endl;
47     }
48     cout << endl << "*********" << endl;
49     /*v = { 2, 3,5 };
50     Res = s.combinationSum(v, 8);
51     for (auto &a : Res) {
52         for (auto b : a)
53             cout << b << "  ";
54         cout << endl;
55     }
56     cout << endl << "*********" << endl;
57 */
58 
59 
60 }

 

转载于:https://www.cnblogs.com/zzw1024/p/10566913.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值