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

LeetCode "House Robber II"

时间:2015-05-20 13:09:06      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

A high quality DP problem to work on. It is not an merely educational DP, it is subtle.

Basic ideas:
  1. Run original DP twice, 1st with num[0] selected, 2nd with num[0] not selected
  2. Since it is circular arrangement, if 1st is assumed to be selected, we should not consider the last element

class Solution {
public:
    int _rob(vector<int> &num) {
        size_t len = num.size();

        int inc = num[0];
        int exc = 0;
        for (int i = 1; i < len - 1; i++) // Note: we skipped the last element
        {
            int old_inc = inc;
            inc = num[i] + exc;
            exc = std::max(exc, old_inc);
        }

        return std::max(inc, exc);
    }

    int rob(vector<int> &num) {
        size_t len = num.size();
        if (len == 0) return 0;

        // num[0] is selected
        int rob1 = _rob(num);

        // num[0] is not selected
        vector<int> in2;
        in2.insert(in2.end(), num.begin() + 1, num.end());
        in2.push_back(num[0]);
        int rob2 = _rob(in2);
        
        return std::max(rob1, rob2);
    }
};

LeetCode "House Robber II"

标签:

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

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