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

[动态规划] leetcode 213 House Robber II

时间:2019-08-10 14:09:41      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:obb   for   ++   ref   ==   动态   use   href   cto   

problem: https://leetcode.com/problems/house-robber-ii/

        多状态转换dp。我的方法是维护了四个状态。用两趟dp的基本思想也是多个状态。

class Solution {
public:
    int rob(vector<int>& nums) {
        int n = nums.size();
        vector<int> robber(n + 1, 0);
        vector<int> norobber(n + 1, 0);
        vector<int> nofirst_robber(n + 1, 0);
        vector<int> nofirst_norobber(n + 1, 0);
        for(int i = 0;i < n;i++)
        {
            if(i == 0)
            {
                nofirst_robber[i + 1] = nofirst_norobber[i];
                nofirst_norobber[i + 1] = max(nofirst_robber[i], nofirst_norobber[i]);                
            }
            else
            {
                nofirst_robber[i + 1] = nofirst_norobber[i] + nums[i];
                nofirst_norobber[i + 1] = max(nofirst_robber[i], nofirst_norobber[i]);                
            }
            if(i == n - 1 && i != 0)
            {
                robber[i + 1] = norobber[i];
                norobber[i + 1] = max(robber[i], norobber[i]); 
            }
            else
            {
                robber[i + 1] = norobber[i] + nums[i];
                norobber[i + 1] = max(robber[i], norobber[i]);
            }
        }
        return max({robber[n], norobber[n], nofirst_robber[n], nofirst_norobber[n]});
    }
};

 

[动态规划] leetcode 213 House Robber II

标签:obb   for   ++   ref   ==   动态   use   href   cto   

原文地址:https://www.cnblogs.com/fish1996/p/11331152.html

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