码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Combination Sum II"

时间:2014-07-31 05:22:25      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   for   

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

bubuko.com,布布扣
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

LeetCode "Combination Sum II",布布扣,bubuko.com

LeetCode "Combination Sum II"

标签:des   style   blog   http   color   os   io   for   

原文地址:http://www.cnblogs.com/tonix/p/3879828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!