Open azl397985856 opened 5 months ago
if len(nums) == 1: return nums[0]
dp = [0] * len(nums)
dp[0], dp[1] = nums[0], max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i-1], dp[i-2]+nums[i])
return dp[-1]
动态规划 python3代码
class Solution:
def rob(self, nums: List[int]) -> int:
dp = [0] * len(nums)
for i in range(len(nums)):
if i ==0:
dp[i]=nums[i]
elif i==1:
dp[i]=max(nums[:i+1])
else:
dp[i]=max(dp[i-1],dp[i-2]+nums[i])
return dp[-1]
class Solution: def rob(self, nums: List[int]) -> int: prev = 0 curr = 0
for i in nums:}
temp = max(curr, prev + i)
prev = curr
curr = temp
# 循环结束时,curr 表示 dp[k],prev 表示 dp[k-1]
return curr
198. 打家劫舍
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/house-robber/
前置知识
暂无
题目描述