代码随想录day48|198. 打家劫舍213. 打家劫舍 II337. 打家劫舍 III

198. 打家劫舍

class Solution:
    def rob(self, nums: List[int]) -> int:
        #dp数组 dp[i]代表包含下标i能偷的最大钱数
        if len(nums) == 1:
            return nums[0]
        dp = [0]*len(nums)
        dp[0] = nums[0]
        dp[1] = max(nums[0],nums[1])
        for i in range(2,len(nums)):
            dp[i] = max(dp[i-1],dp[i-2]+nums[i])
        return dp[len(nums)-1]

213. 打家劫舍 II 将环变成线性,只需要考虑首尾,包含首不包含尾,包含尾不包含首(准确来讲不是包含而是考虑)二者取最大值

class Solution:
    def rob(self, nums: List[int]) -> int:
        if len(nums)<=2:
            return max(nums)
        return max(self.rob_range(nums[:-1]),self.rob_range(nums[1:]))
        
    def rob_range(self, nums: List[int]) -> int:
        #dp数组 dp[i]代表包含下标i能偷的最大钱数
        dp = [0]*len(nums)
        dp[0] = nums[0]
        dp[1] = max(nums[0],nums[1])
        for i in range(2,len(nums)):
            dp[i] = max(dp[i-1],dp[i-2]+nums[i])
        return dp[len(nums)-1]

337. 打家劫舍 III

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rob(self, root: Optional[TreeNode]) -> int:
        # dp数组是当前节点偷与不偷对应的最大金额
        result=self.rob_tree(root)
        return max(result)
    def rob_tree(self,cur):
        if cur == None:
            return [0,0]
        left = self.rob_tree(cur.left)
        right = self.rob_tree(cur.right)

        val0 = cur.val + left[1] + right[1]
        val1 = max(left)+max(right)
        return [val0,val1]

你可能感兴趣的:(算法,leetcode,职场和发展)