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 (a1, a2, … , 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] 

class Solution {
public:
    int _sum(vector<int> tmp) {
        int sum = 0;
        int i;
        for (i=0; i<tmp.size(); i++){
            sum+= tmp[i];
        }
        return sum;
    }

    void combination(vector<int>& candidates, vector<vector<int>> &res, vector<int> tmp, int target, int start) {
        //计算选择集的和
        int sum = _sum(tmp);
        if (start >= candidates.size() || sum > target || sum + candidates[start] > target) {
            return;
        }
        //计算该选择集是否可以包含当前数,包含多少个
        int num_add = (target - sum) / candidates[start];
        int num_mod = (target - sum) % candidates[start];

        int i = 0;
        //循环num_add次,每次增加一个当前数到选择集中,然后将当前数设置为下一个,进行计算
        while (i < num_add) {
            i++;
            sum += candidates[start];
            tmp.push_back(candidates[start]);
            //避免函数调用浪费时间
            if (start < candidates.size() -1) {
                combination(candidates, res, tmp, target, start + 1);
            }
        }
        //如果当前选择集合的和正好等于target,加入结果集
        if (num_add && i == num_add && !num_mod) {
            res.push_back(tmp);
        }
        //将选择集合中所有的当前数去掉,然后计算不包含当前数时
        while (i--) {
            tmp.pop_back();
        }
        combination(candidates, res, tmp, target, start + 1);
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<int> tmp = {};
        int start = 0;
        vector<vector<int>> res;
        sort(candidates.begin(), candidates.end());
        combination(candidates, res, tmp, target, start);
        return res;
    }
};

 

你可能感兴趣的:(Combination Sum)