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 @ 2025-01-09 15:37  ouyangxx  阅读(27)  评论(0)    收藏  举报