LeetCode 198. House Robber DP
阿新 • • 發佈:2022-05-12
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night
Given an integer array nums
representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Solution
很顯然的一個思路就是開一維表示選了還是沒選當前的數:\(dp[i][0]\) 表示以 \(i\) 結尾的序列,沒選 \(i\) 的最大值,\(dp[i][1]\) 則是表示選了第 \(i\) 個。對於轉移方程:
\[\begin{align} dp[i][0] &= \max(dp[i-1][0],dp[i-1][1])\\ dp[i][1] &= dp[i-1][0] + nums[i] \end{align} \]點選檢視程式碼
class Solution { private: int dp[105][2]; public: int rob(vector<int>& nums) { int n = nums.size(); if(n==1)return nums[0]; else{ dp[0][1] = nums[0]; dp[0][0] = 0; for(int i=1;i<n;i++){ dp[i][0] = max(dp[i-1][0],dp[i-1][1]); dp[i][1] = dp[i-1][0]+nums[i]; } return max(dp[n-1][0],dp[n-1][1]); } } };