Tuesday, May 14, 2013

Leetcode: Combination Sum II in C++



Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
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:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6] 

For example, given candidate set 10,1,2,7,6,1,5 and target 8

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())
        {
            int count =1;
            while(i+1<candidates.size()&&candidates[i]==candidates[i+1])
            {
                count++;
                i++;
            }
            helper(result, current, target, candidates, i+1); 
            while(count>0)
            {
                current.push_back(candidates[i]);
                target -= candidates[i];
                helper(result, current, target, candidates, i+1); 
                count--;
            }
               
        }
        return;
    }
    vector<vector<int> > combinationSum2(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