198. 打家劫舍

  1. [题目链接](198. 打家劫舍 - 力扣(LeetCode))

  2. 解题思路:比较经典的动态规划。从左往右尝试。来到index位置,有两种选择,不偷,那么就去index+1位置做决策,偷,那么就去index + 2做决策。直接加dp表即可。

  3. 代码

    class Solution:
    def process(self, nums, index, dp):
    if index >= len(nums):
    return 0
    if dp[index] != -1:
    return dp[index]
    # 偷
    yes = self.process(nums, index + 2, dp) + nums[index]
    # 不偷
    no = self.process(nums, index + 1, dp)
    dp[index] = max(yes, no)
    return dp[index]
    def rob(self, nums: List[int]) -> int:
    dp = [-1 for _ in range(len(nums)) ]
    return self.process(nums, 0, dp)
posted @   ouyangxx  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示