Tuesday, May 14, 2013

Leetcode: Combination Sum in C++



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.
A solution set is:
[7]
[2, 2, 3] 

For example, given candidate set 2,3,6,7 and target 7

Solution:

void helper(vector<vector<int> > &result,vector<int> current, int target,vector<int> &candidates, int i )
    {
        if(target<0)
        return;
        if(target==0)
        {
            result.push_back(current);
            return;
        }
        if(i < candidates.size())
        {
            helper(result, current, target, candidates, i+1); 
            int t = target;
            while(t>=0)
            {
                current.push_back(candidates[i]);
                t = t- candidates[i];
                helper(result, current, t, candidates, i+1);
            }
        }
        return;
    }
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        sort(candidates.begin(),candidates.end());
        vector<vector<int> > result;
        vector<int> current;
        helper(result, current, target, candidates, 0);
        return result;
    }

No comments:

Post a Comment