Wednesday, September 17, 2014

[Leetcode] 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.
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] 
Analysis:
It is basically to find all subset and save the results when target = 0. Notice that since the number could be used unlimited time, so in the code, dfs call should be i rather than i+1. The current A[i] could be used until sum > n and till then, i = i + 1.


class Solution {
public:

void dfs(vector<vector<int> >& ret, int target, int m, vector<int>& candidates, vector<int>& nums)
{
 if (target == 0)
 {
  ret.push_back(nums);
 }
 else if (target < 0)
 {
     return;
 }
 else
 {
  for (int i = m; i < candidates.size(); i++)
  {
   nums.push_back(candidates[i]);
   dfs(ret, target -candidates[i], i, candidates, nums);
   nums.pop_back();
  }
 }
}

    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int> > ret;
        vector<int> nums;
        dfs(ret, target, 0, candidates, nums);
        
        return ret;
    }
};

No comments:

Post a Comment