Thursday, December 11, 2014

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 (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]

Backtracking:

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<vector<int>> res;
        int n=candidates.size();
        sort(candidates.begin(),candidates.end());
        if (n==0||candidates[0]>target)
           return res;
        vector<int> r;
       
        dfs(res,candidates,target,0, r, 0);
        return res;
    }
   
    void dfs(vector<vector<int>> &res, vector<int> &cs, int t, int sum, vector<int> &r, int idx)
    {
        if (sum==t)
        {
            res.push_back(r);
        }
        else
        {
            int n=cs.size();
            for (int i=idx; i<n; i++)
            {
                if (sum+cs[i]>t)
                    return;
                r.push_back(cs[i]);
                dfs(res,cs,t,sum+cs[i],r,i);      //pay attention to this
                r.pop_back();
            }
        }
       
    }
};

No comments:

Post a Comment