Monday, November 25, 2013

LeetCode Problem : Combination Sum

Problem


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.
For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

Code

void DFS_cs(int pos,int k,int target,const vector<int> &num,
vector<int> &out,vector<vector<int> > &result)
{
    if(target == 0){
        result.push_back(vector<int>(out.begin(),out.begin() + pos));
        return;
    }
    if(target < 0)
        return;
    if(pos == out.size())
        out.resize(2*pos + 1);

    for(int i = k;i < num.size();++i){
        out[pos] = num[i];
        DFS_cs(pos + 1,i,target - num[i],num,out,result);
    }
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    vector<vector<int> >result;
    vector<int> out;
    sort(candidates.begin(),candidates.end());
    DFS_cs(0,0,target,candidates,out,result);
    return result;
}

No comments:

Post a Comment