首页 > 代码库 > Combination Sum -- leetcode

Combination Sum -- leetcode

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] 



该算法在leetcode上,实际运行时间为29ms。

基本思路为,candidates的每个元素选择合适的重复次数(包括0次),进行组合,看结果是否为target。

数组solution中元素的值,为对应的candidate元素的使用次数。

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<vector<int> > result;

        sort(candidates.begin(), candidates.end());
        vector<int> solution(candidates.size());

        helper(result, solution, candidates, 0, target);
        return result;
    }

    void helper(vector<vector<int> >&result, vector<int> &solution, const vector<int> &candidates, int index, int target) {
        if (index == candidates.size()) return;
        solution[index] = 0;

        while (target > 0) {
                helper(result, solution, candidates, index+1, target);

                solution[index]++;
                target -= candidates[index];
        }

        if (!target) {
                result.push_back(vector<int>());
                for (int i=0; i<=index; i++) {
                        for (int j=0; j<solution[i]; j++) {
                                result.back().push_back(candidates[i]);
                        }
                }
        }
    }
};


以上算法参考自

https://oj.leetcode.com/discuss/20994/33ms-c-recursive-solution

他用了乘法和除法,每个元素的被使用的次数从最高到低递减偿试。 

我将他的乘法和除法去掉,改成从低到高进行偿试。


原来算法的执行时间为33ms。我改后为29ms。 不知道这少掉的4ms是不是从剩法除法中挤出来的,或者是机器实际执行时间的随机性导致。

Combination Sum -- leetcode