Monday, October 20, 2014

Combination Sum II

class Solution {

public:
    vector<vector<int>> combinationSum2(vector<int> &candidates, int target) {
        vector<vector<int>> res;
        sort(candidates.begin(), candidates.end());
        vector<int> com;
        combinationSumRe(candidates, target, 0, com, res);
        return res;
    }

    void combinationSumRe(const vector<int> &num, int target, int start, vector<int> &com, vector<vector<int>> &res)
    {
        if (target < 0) { return; }

        if (target == 0) {
            res.push_back(com);
            return;
        }
        for (int i = start; i < num.size(); ++i) {
            if(i>start&&num[i]==num[i-1]) continue;//attention, here it is i>start, not i>0
            com.push_back(num[i]);
            combinationSumRe(num, target-num[i], i+1, com, res);
            com.pop_back();
           
        }
    }
};

No comments:

Post a Comment