[leetcode] 337. House Robber III @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/88761758

原题

https://leetcode.com/problems/house-robber-iii/

解法

DFS. 定义dfs函数, 返回两个值: 从当前节点偷能获取的最大值rob_now和从子节点开始偷能获得的最大值rob_later. Base case是当root为空时, 返回(0, 0). 如果从当前节点偷, 那么左右的子节点不能偷, 如果从子节点开始偷, 那么总金额为两个节点能偷到的最大值的和.

rob_now = root.val + left[1] + right[1]
rob_latter = max(left) + max(right)

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def rob(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """        
        def dfs(root):
            # return the max money if rob this root and the max money if not rob this root
            if not root: return (0, 0)
            left, right = dfs(root.left), dfs(root.right)
            rob_now = root.val + left[1] + right[1]
            rob_later = max(left) + max(right)            
            return (rob_now, rob_later)
        
        return max(dfs(root))

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/88761758