美文网首页
337. House Robber III

337. House Robber III

作者: GoDeep | 来源:发表于2018-05-02 16:03 被阅读0次
image.png

需要memo

class Solution(object):
    def rob(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        memo = {}
        
        def helper(root, f):
            if not root: return 0
            if (root,f) in memo: return memo[(root,f)]
            l0, l1 = helper(root.left,0), helper(root.left,1)
            r0, r1 = helper(root.right,0), helper(root.right,1)
            if f: 
                memo[(root,f)] = root.val+l0+r0
                return root.val+l0+r0
            else: 
                memo[(root,f)] = max(l0,l1)+max(r0,r1)
                return max(l0,l1)+max(r0,r1)
            
        if not root: return 0
        return max(helper(root, 0), helper(root, 1))

相关文章

网友评论

      本文标题:337. House Robber III

      本文链接:https://www.haomeiwen.com/subject/ihecrftx.html