[leetcode] 39. Combination Sum

Question:

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

Solution:

简单递归,对candidates的每一个位置的元素进行以下操作:
1. 若target == candidates[i], 则组成了一个解
2. 若target > candidates[i], 则继续往下递归求解,只不过递归的target为target = target - candidates[i],candidates为candidates[i]以及后面的元素(避免得到重复解,因为若target - candidates[i] - candidates[j] 且 j < i 能得到解的话,那么在第j次循环时就已经得到这个解了)。
我没有使用for循环执行上面的循环递归,而是用了while,每次删掉第一个元素得到新的candidates,即为2中的“candidates[i]以及后面的元素”。

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> ret;
        vector<int> ans;
        helper(ret, candidates, target, ans);
        return ret;
    }

    void helper(vector<vector<int>> & ret, vector<int> candidates, int target, vector<int> ans) {
        while (!candidates.empty()) {
            vector<int> tmp = ans;
            tmp.push_back(candidates[0]);
            if (target == candidates[0]) {
                ret.push_back(tmp);
            } else if (target > candidates[0]) {
                int t = target - candidates[0];
                helper(ret, candidates, t, tmp);
            }
            candidates.erase(candidates.begin());
        }
    }
};

Solution 2:

用上面的方法做完后,运行时间是29ms,发现分布图里自己的运行时间是非常慢的,随手点开了一个9ms的答案。发现他的思路和我的是一样的,但是有以下地方不同:
他的combination对应我的ans数组,而他一直使用引用,由始至终只使用一个数组,巧妙运用pop_back还原成原来的数组,而我在递归过程中生成了大量的数组。
使用for循环与下标就可以只使用同一个candidates数组,而我使用while,每次都要传递新的candidates数组,又会生成大量新的数组,占用时间。

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>&candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> res;
        vector<int> combination;
        CombiantionNums(candidates, target, res, combination, 0);
        return res;
    }
private:
    void CombiantionNums(vector<int>&candidates, int target, vector<vector<int>>&res, vector<int>&combination, int begin) {
        if (!target) {
            res.push_back(combination);
            return ;
        }
        for (int  i = begin; i != candidates.size() && target >= candidates[i]; i++)
        {
            combination.push_back(candidates[i]);
            CombiantionNums(candidates, target - candidates[i], res, combination, i);
            combination.pop_back();
        }
    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值