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

思路:这道题显然可以用递归做。将7进行分解,相当于一个多叉树。遍历数组,

判断target减去当前数,如果>=0则进行下层分解,如果小于则回溯。由于分解的数是非递减的,还需要判断当前

分解的数>=已分解的数的最大值,代码如下:

class Solution {
private:
    vector<vector<int> > res;
    vector<int> perRes;
public:
    void combinationSumHelper(vector<int> candidates, int target, int pos, int left) {
        if (target == 0) {
            res.push_back(perRes);
        }
        else {
            int len = candidates.size();
            int i;
            for(i=0; i<len; ++i) {
                perRes.resize(pos+1);
                if (target-candidates[i] >= 0 && candidates[i] >= left) {
                    perRes[pos] = candidates[i];
                    combinationSumHelper(candidates, target-candidates[i], pos+1,candidates[i]);
                }
            }
        }
    }
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        res.clear();
        if (candidates.empty()) {
            return res;
        }
        perRes.clear();
        combinationSumHelper(candidates,target,0,0);
        return res;
    }
};   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值