Friday, October 11, 2013

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 (a1, a2, … , ak) must be in non-descending order. (ie, a1a2 ≤ … ≤ 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]
Solution: DP; sort the candidates first; pay attention to eliminating duplicate combinations [line 8].

class Solution {
public:
    void combinationSumHelper(vector<int> &candidates, int cur, int start, int target, vector<vector<int> > &ret, vector<int> r){
        if(cur==target){
            ret.push_back(r);
            return;
        }
        for(int i=start; i<candidates.size(); ++i){
            if(cur+candidates[i]<=target){
                r.push_back(candidates[i]);
                combinationSumHelper(candidates, cur+candidates[i], i, target, ret, r);
                r.pop_back();
            }
        }
    }
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > ret;
        if(target<=0 || candidates.empty()) return ret;
        sort(candidates.begin(), candidates.end());
        vector<int> r;
        combinationSumHelper(candidates, 0, 0, target, ret, r);
        return ret;
    }
};

No comments:

Post a Comment