首页 > 代码库 > LeetCode "Combination Sum II"

LeetCode "Combination Sum II"

The only difference with version I is: one number can only be used once:

class Solution {public:    vector<vector<int> > ret;    struct Rec    {        Rec() : sum(0) {}        int sum;        vector<int> v;    };    void go(vector<int> cands, int level, struct Rec currRec, int target)    {        if(currRec.sum == target)        {            ret.push_back(currRec.v);            return;        }        int desire = target - currRec.sum;                int last = std::numeric_limits<int>::max();        for(int i = 0; i < cands.size(); i ++)        {            int cand = cands[i];            if(cand <= desire && cand != last)            {                if(!currRec.v.empty())                {                    if(cand < currRec.v[currRec.v.size() - 1]) continue;                }                Rec newRec = currRec;                newRec.sum += cand;                newRec.v.push_back(cand);                vector<int> newCands = cands;                newCands.erase(std::find(newCands.begin(), newCands.end(), cand));                                go(newCands, level + 1, newRec, target);                    last = cand;            }        }    }    vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {        if(candidates.empty()) return ret;        std::sort(candidates.begin(), candidates.end());           go(candidates, 0, Rec(), target);        return ret;    }};
View Code