标签: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