Tuesday, January 6, 2015

[LeetCode] 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 toT.
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.
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]
Note: how to remove the duplicate combination?
class Solution {
public:
    void calc(vector<vector<int> >&res, vector<int> &candidates, 
              int target, vector<int> & row, int s)
    {
        if(target == 0)
        {
            res.push_back(row);
            return;
        }
        for(int k = s;k<candidates.size() && target >= candidates[k];k++)
        {
            //if there are duplicate elements in the same loop
            //skip them, for it's already handled in previous BT
            if(k!=s && candidates[k-1] == candidates[k]) continue;
            row.push_back(candidates[k]);
            calc(res, candidates, target-candidates[k], row, k+1);
            row.pop_back();
        }
    }
    vector<vector<int> > combinationSum2(vector<int> &candidates, 
                                         int target) 
    {
        vector<vector<int> > res;
        vector<int> row;
        sort(candidates.begin(), candidates.end());
        calc(res, candidates, target, row, 0);
        return res;
    }
};