DP-LeetCode198. 打家劫舍

1、题目描述

你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。

给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。

2、代码详解

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        if n == 0:
            return 0
        dp = [0] * (n+1)  # 开辟n+1空间,[0, n]
        dp[0] = 0
        dp[1] = nums[0]
        for i in range(2, n+1):
            dp[i] = max(dp[i-1], dp[i-2]+nums[i-1])

        return dp[n]
nums = [3, 1, 2, 4] # 7
s = Solution()
print(s.rob(nums))

https://leetcode-cn.com/problems/house-robber/solution/hua-jie-suan-fa-198-da-jia-jie-she-by-guanpengchn/

https://www.zhihu.com/people/sun-jia-tong-59

数组滚动写法

https://github.com/Light-City/Fight_Alg/blob/master/dp/README.md

发布了184 篇原创文章 · 获赞 225 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/IOT_victor/article/details/105647492
今日推荐