力扣 198. 打家劫舍

动态规划方程

状态转移: $ f(i) = max(f(i - 2) + cur, f(i - 1)) $

初始化: $dp[0]=0,dp[1]=nums[0]$

一维动态规划

1
2
3
4
5
6
7
def rob(nums):
# 动态规划
dp = [0] * (len(nums) + 1)
dp[1] = nums[0]
for i in range(1, len(nums)):
dp[i + 1] = max(nums[i] + dp[i - 1],dp[i])
return dp[-1]

空间优化动态规划

1
2
3
4
5
6
7
def rob(nums):
# 动态规划
ppre, pre, cur = 0, nums[0], 0
for i in range(1, len(nums)):
cur = max(nums[i] + ppre, pre)
ppre, pre = pre, cur
return pre
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信