LeetCode 39. Combination Sum

本文针对给定候选数集合及目标数,寻找所有可能的组合,使得候选数之和等于目标数。通过递归方法实现,确保解决方案集不包含重复组合。

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set [2, 3, 6, 7] and target 7
A solution set is: 

[
  [7],
  [2, 2, 3]
] 

Subscribe to see which companies asked this question

 

用递归做该题显得复杂度很高, 但是我觉得没有什么更好的办法. 用递归最关键的是明确每一步所需要完成的操作, 这样写起来会比较容易.

 

 1 class Solution {
 2 public:
 3     void solve(int depth, int maxdepth, int target, vector<vector<int> >& result,vector<int>& candidates, vector<int>& ret)
 4     {
 5         for(int i=0;i<=target/candidates[depth];i++){
 6             if(target-i*candidates[depth]<0)break;
 7             ret[depth]=i;
 8 
 9             if(target-i*candidates[depth]==0){//完成目标,记录下来
10                 vector<int> tmp;
11                 tmp.clear();
12                 for(int i=0;i<=maxdepth;i++)
13                     for(int j=0;j<ret[i];j++){
14                         tmp.push_back(candidates[i]);
15                     }
16                 result.push_back(tmp);
17                 return;
18             }
19             
20             if(depth+1==maxdepth+1){//最后一个数字的处理
21                 continue;
22             }
23 
24             solve(depth+1,maxdepth,target-i*candidates[depth],result,candidates,ret);
25         }
26     }
27 
28     vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
29         vector<vector<int> > result;
30         sort(candidates.begin(),candidates.end());
31         vector<int> ret;
32         ret.resize(candidates.size()+1);
33         solve(0,candidates.size()-1,target,result,candidates,ret);
34 
35         return result;
36     }
37 };

 

转载于:https://www.cnblogs.com/gremount/p/5953559.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值