[动态规划] leetcode 213 House Robber II
Posted fish1996
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[动态规划] leetcode 213 House Robber II相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章