每日算法之三十一:Combination Sum

给定一个整数序列,求解一个子序列,子序列之和等于给定目标值。子序列满足以下条件:

1)子序列是有序的

2)子序列的元素个数不限,可以是给定元素的重复元素。

3)结果中的子序列是唯一的

原题描述如下:

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.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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] 

分析如下:

此题很合适用回溯法来解决。调用间的关系可用调用树描述,第一层只有2,接下来,递归循环再次调用2,和为4,小于7,再次调用2,和为6,再次之后是8,大于7,因此这一层不再考虑,以此即可,如果存在等于7的就加入结果集中,这在下面的代码中很明显。

<span style="font-size:18px;">class Solution {
private:
    void com(vector<int> &candidates,int start,int sum,int target,
             vector<int> &path,vector<vector<int> > &res)
    {
        if(sum>target)
            return ;
        if(sum == target)
        {
            res.push_back(path);//加入到结果集中
            return;
        }
        int len = candidates.size();
        for(int i = start;i<len;i++)//从start开始要,基于上一次调用树
        {
            path.push_back(candidates[i]);
            com(candidates,i,sum+candidates[i],target,path,res);//从i开始,因为小于i的都不再是正序。
            path.pop_back();//有进就有出
        }
    }
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<vector<int> > res;
        vector<int> path;
        sort(candidates.begin(),candidates.end());
        com(candidates,0,0,target,path,res);//参数设置要合理
        return res;
    }
};</span>



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值