Thursday, December 11, 2014

Combination Sum II

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 (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 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]

Backtracking. Solution 1 is faster than solution 2.


Solution 1:

class Solution {
public:
    vector<vector<int> > combinationSum2(vector<int> &num, int target) {
        vector<vector<int>> res;
        int n=num.size();
        sort(num.begin(), num.end());
        if (n==0||num[0]>target)
           return res;
        vector<int> r;
        vector<int> prev;
        dfs(num, res,r, 0, target,0);
        return res;
    }
   
    void dfs(vector<int> &n, vector<vector<int>> &res, vector<int> &r, int sum, int t, int start)
    {
        if (sum==t)
        {
            res.push_back(r);
            return;
        }
        else
        {
            int ns=n.size();
            int previous = -1;
            for (int i=start; i<ns; i++)
            {
                if (n[i]+sum>t)
                   return;
                if (previous==n[i]) continue;
                previous = n[i];

                r.push_back(n[i]);
                dfs(n,res,r,sum+n[i],t,i+1);
                r.pop_back();
            }
        }
    }
};

Solution 2:
class Solution {
public:
    vector<vector<int> > combinationSum2(vector<int> &num, int target) {
        vector<vector<int>> res;
        int n=num.size();
        sort(num.begin(), num.end());
        if (n==0||num[0]>target)
           return res;
        vector<int> r;
        vector<int> prev;
        dfs(num, res,r, 0, target,0);
        return res;
    }
   
    void dfs(vector<int> &n, vector<vector<int>> &res, vector<int> &r, int sum, int t, int start)
    {
        if (sum==t)
        {
            for (int i=0; i<res.size(); i++)
            {
                if (res[i]==r)
                  return;
            }
            res.push_back(r);
            return;
        }
        else
        {
            int ns=n.size();
            for (int i=start; i<ns; i++)
            {
                if (n[i]+sum>t)
                   return;
                r.push_back(n[i]);
                dfs(n,res,r,sum+n[i],t,i+1);
                r.pop_back();
            }
        }
    }
};

No comments:

Post a Comment