39. Combination Sum

problem description

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.

  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

algorithm thought

组合数相加最后和为target,基本需要遍历所有集合。使用回溯法得到所有的集合,判断和是否为target。由于数字相加如果已经大于target,就没必要继续遍历了。所以加入了剪枝策略,首先sort数组,为了先遍历小数字后遍历大数字。然后在进入下一个函数之前判断是否满足剪枝策略,如果满足,就不进入函数。

code

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

algorithm analysis

回溯法世家复杂度是O(2^n),很慢,但是这里加入了剪枝策略,还是一定程度上加快了运行速度的。

Last updated