当前位置:   article > 正文

代码随想录训练营第III期--048--python_代码随想录 python

代码随想录 python
#  198.打家劫舍 
class Solution:
    def rob(self, nums):
        if len(nums) == 0:
            return 0
        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-2] + nums[i], dp[i-1])
        return dp[-1]
#  213.打家劫舍II  
class Solution:
    def rob(self, nums):
        if len(nums) == 1: return nums[0]
        v1 = self.roblist(nums[1:])
        v2 = self.roblist(nums[:-1])
        return max(v1, v2)
    
    def robRange(self, nums):
        l = len(nums)
        dp = [0] * l 
        dp[0] = nums[0]
        for i in range(1, l):
            if i == 1:
                dp[i] = max(dp[i-1], nums[i])
            else:
                dp[i] = max(dp[i-1], dp[i-2] + nums[i])
        return dp[-1]
#  337.打家劫舍III
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):
        dp = self.traversal(root)
        return max(dp)
    def traversal(self, node):
        if not node: return (0, 0)

        left = self.traversal(node.left)
        right = self.traversal(node.right)

        val_0 = max(left[0], left[1]) + max(right[0], right[1])

        val_1 = node.val + left[0] + right[0]

        return (val_0, val_1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/618883
推荐阅读
相关标签
  

闽ICP备14008679号