[LeetCode]198. House Robber
198. House Robber
思路
notrob_dp[i] = max(notrob_dp[i-1], rob_dp[i-1]) (if not rob current home)
rob_dp[i] = notrob_dp[i-1] + nums[i] (if rob current home)class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
elif len(nums) == 1:
return nums[0]
elif len(nums) == 2:
return max(nums)
l = len(nums)
rob_dp = [nums[0]] + [0] * (l-1)
notrob_dp = [0] * l
for i in range(1, l):
# 偷当前房屋
cur_rob = notrob_dp[i-1] + nums[i]
# 不偷当前房屋
notrob_dp[i] = max(notrob_dp[i-1], rob_dp[i-1])
# 更新
rob_dp[i] = cur_rob
return max(rob_dp[l-1], notrob_dp[l-1])
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
rob, not_rob = 0, 0
for i in range(len(nums)):
cur_rob = not_rob + nums[i]
not_rob = max(not_rob, rob)
rob = cur_rob
return max(rob, not_rob)
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法

浙公网安备 33010602011771号