题解 | #打家劫舍(一)#
打家劫舍(一)
https://www.nowcoder.com/practice/c5fbf7325fbd4c0ea3d0c3ea6bc6cc79
class Solution { public: int rob(vector<int>& nums) { // write code here int n = nums.size(); if (n == 1)return nums[0]; vector<int>dp(n); for (int i = 0; i < n; i++) { if (i < 2) { dp[i] = nums[i]; } else if (i == 2) { dp[i] = nums[i] + nums[i - 2]; } else { dp[i] = max(dp[i - 2] + nums[i], dp[i - 3] + nums[i]); } } return max(dp[n - 1], dp[n - 2]); } };