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.

For example, given candidate set 2,3,6,7 and target 7, A solution set is:

[7]

[2, 2, 3]

分析:

已经逐渐开始习惯dfs的几个退出条件和带入参数,比方说这道题,因为可以重复使用elements,所以带入的start应该是上一层的i。

解法:

class Solution {
public:
    /**
     * @param candidates: A list of integers
     * @param target:An integer
     * @return: A list of lists of integers
     */
    int getSum(vector<int> instance) {
        int sum = 0;
        for (int i = 0; i < instance.size(); i++) {
            sum += instance[i];
        }
        return sum;
    }


    void dfs(vector<int> candidates, 
                vector<int> instance, 
                vector<vector<int> >& res, 
                int start,
                int target) {

        if (getSum(instance) > target) {
            return;
        }

        if (getSum(instance) == target) {
            res.push_back(instance);
            return;
        }

        for (int i = start; i < candidates.size(); i++) {
            instance.push_back(candidates[i]);
            dfs(candidates, instance, res, i, target);
            instance.pop_back();
        }
    }

    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        // write your code here
        if (candidates.size() == 0) {
            return vector<vector<int> >();
        }

        if (target < 0) {
            return vector<vector<int> >();
        }

        sort(candidates.begin(), candidates.end() );

        vector<int> instance;
        vector<vector<int> > res;

        dfs(candidates, instance, res, 0, target);
        return res;
    }
};

results matching ""

    No results matching ""