【LeetCode】39. Combination Sum

算法小白,最近刷LeetCode。希望能够结合自己的思考和别人优秀的代码,对题目和解法进行更加清晰详细的解释,供大家参考^_^

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]
]

给定一个无重复元素的序列和一个目标值,序列中的每个数字可以不使用,或使用多次,输出所有和等于目标值的可行方案。

使用递归方法,首先对元素排序,然后每次选择一个元素0次或a次,从目标值中减去所选择数的和值,再次进行递归,当和值变成0时,说明找到了一个可行方案,当然也要注意不要越界,同时当下一个数字比当前目标值大时,说明当前方案不可行,递归返回。

class Solution {
public:
    // 递归函数:candidates是元素集合,diff是当前目标和值,begin是本次要选数字的索引
    // tmp为生成序列,res为方案结果集
    void fun(const vector<int> &candidates, int diff, int begin, vector<int> tmp, vector<vector<int>> &res) {
        if (diff == 0) { res.push_back(tmp); return ; } // 和值为0,说明找到一个可行方案,将该方案加入到结果集中
        if (begin == candidates.size()) return ; // 索引越界,返回
        if (diff < candidates[begin]) return; // 目标和值小于当前值,该方案不可行,返回

        for (int i = 0; i <= diff/candidates[begin]; ++i) { // 选择该元素0次或x次,x<=diff/当前元素值
            int ii = i; 
            vector<int> tmp2(tmp); // 保存当前递归状态,复制一个临时对象作为下次递归的参数
            while (ii--) tmp2.push_back(candidates[begin]); // 将其加入到序列中i次
            fun(candidates, diff-candidates[begin]*i, begin+1, tmp2, res); // 进行递归
        }

    }

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end()); // 排序
        vector<vector<int>> res;    
        fun(candidates, target, 0, vector<int>{}, res); // 调用递归函数 
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值