Monday, February 3, 2014

[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 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 (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] 
Algorithm:
1. This problem is the same as the previous one, we can use DFS and take the input as a tree.
2. Should be careful that the solution set must not contain duplicate combinations. 
3. remember to pop_back the path after each recursion finished.
My Code:

bool uniquesum(vector > res, vector check){
        for(int i = 0; i < res.size(); ++i){
            if(std::equal(res[i].begin(), res[i].end(), check.begin()))
                return false;
        }
        return true;
        
    }
    void dfs(int left, vector & num, int target, vector &path, vector > &res){
        if(!target) {
            if(uniquesum(res, path))
                res.push_back(path);
            return;
        }
        for(int i = left; i < num.size(); ++i){
            if(num[i] > target) break;
            path.push_back(num[i]);
            dfs(i+1, num, target-num[i], path, res);
            path.pop_back();
        }
        return;
    }

    vector > combinationSum2(vector &num, int target) {
        vector > res;
        if(num.empty()) return res;
        sort(num.begin(), num.end());
        vector path;
        dfs(0, num, target, path, res);
        return res;
    }

No comments:

Post a Comment