现在的位置: 首页 > 综合 > 正文

Combination Sum

2018年04月01日 ⁄ 综合 ⁄ 共 1150字 ⁄ 字号 评论关闭

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;
    }
};   
【上篇】
【下篇】

抱歉!评论已关闭.