Friday, October 11, 2013

Combination Sum II [Leetcode]

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]

Solution: the basis idea is the same as Combination Sum problem, but here you may need to pay special attention to making sure that each number in C only be used once in each combination [Lines 8, 9 and 11].

class Solution {
public:
    void combinationSumHelper(vector<int> &num, int cur, int start, int target, vector<vector<int> > &ret, vector<int> r){
        if(cur==target){
            ret.push_back(r);
            return;
        }
        for(int i=start; i<num.size(); ++i){
            if(cur+num[i]<=target && (i==start || num[i]!=num[i-1])){
                r.push_back(num[i]);
                combinationSumHelper(num, cur+num[i], i+1, target, ret, r);
                r.pop_back();
            }
        }
    }
    
    vector<vector<int> > combinationSum2(vector<int> &num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > ret;
        if(target<=0 || num.empty()) return ret;
        sort(num.begin(), num.end());
        vector<int> r;
        combinationSumHelper(num, 0, 0, target, ret, r);
        return ret;
    }
};

No comments:

Post a Comment