Leetcode刷题记录——198. 打家劫舍

在这里插入图片描述
使用动态规划
子问题:对前i个房屋,能偷到的最高金额是f(i)
边界为f(1) = a[0]
f(2) = max(a[0],a[1])
状态转移方程:f(n) = max(f(n-2)+a(n),f(n-1)),其中a为代表每个房屋中现金数量的list,n>=3

class Solution:
    def rob(self, nums: List[int]) -> int:
        if nums == []:
            return 0
        length = len(nums)

        if length == 1:
            return nums[0]
        elif length == 2:
            return max(nums)
        
        res = 0
        l_2 = nums[0]
        l_1 = max(nums[0],nums[1])
        for i in range(length - 2):
            tempindex = i + 2
            res = max(l_2+nums[tempindex],l_1)
            l_2 = l_1
            l_1 = res

        return res
发布了43 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41545780/article/details/105052261
今日推荐