[Leetcode] 39. Combination Sum 解题报告

本文介绍了一种经典的回溯算法应用——组合求和问题。针对给定的候选数集合及目标值,寻找所有可能的组合使得这些数相加等于目标值。文章提供了两种实现方案并对比了它们的性能差异。

题目

Given a set of candidate numbers (C(without duplicates) 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]
]

思路

凡是需要返回所有可行解的题目,99%都是需要用到回溯法的。但是回溯方式的不同可能造成运行效率的巨大差异。一般而言,对于计算的中间结果(例如本题目中的vector<int>类型的变量line),如果能用引用就尽量用引用,这样效率可以大大提高。

代码

1、采用引用的方式实现(12ms):

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) 
    {
        vector<vector<int>> ret;
        vector<int> line;
        sort(candidates.begin(), candidates.end());
        combination(candidates, target, ret, line);
        return ret;
    }
private:
    void combination(vector<int>& candidates, int target, 
        vector<vector<int>>& ret, vector<int>& line)
    {
        if(target == 0)
        {
            ret.push_back(line);
            return;     //  we should return for the back-tracking
        }
        
        for(int i = 0; i < candidates.size(); ++i)
        {
            if(candidates[i] > target)
                break;
                
            // make sure no smaller integers are added later
            if(line.size() > 0 && candidates[i] < line[line.size() - 1])
                continue;
                
            line.push_back(candidates[i]);
            combination(candidates, target - candidates[i], ret, line);
            line.pop_back();
        }
    }
};
2、采用非引用的方式实现(52ms):

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> ret;
        vector<int> line;
        combination(candidates, target, ret, line, 0);
        return ret;
    }
private:
    void combination(vector<int>& candidates, int target, vector<vector<int>> &ret,
        vector<int> line, int index)
    {
        if(target == 0)
            ret.push_back(line);
        if(index >= candidates.size() || target <= 0)
            return;
        combination(candidates, target, ret, line, index + 1);      // include 0 candidates[index]
        for(int i = 1; target - i * candidates[index] >= 0; ++i)    // include i candidates[index]
        {
            line.push_back(candidates[index]);
            combination(candidates, target - i * candidates[index], ret, line, index + 1);
        }
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值