鱼C论坛

 找回密码
 立即注册
查看: 2166|回复: 0

[学习笔记] Leetcode 337. House Robber III

[复制链接]
发表于 2020-8-1 00:52:37 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

  2. Determine the maximum amount of money the thief can rob tonight without alerting the police.

  3. Example 1:

  4. Input: [3,2,3,null,3,null,1]

  5.      3
  6.     / \
  7.    2   3
  8.     \   \
  9.      3   1

  10. Output: 7
  11. Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
  12. Example 2:

  13. Input: [3,4,5,1,3,null,1]

  14.      3
  15.     / \
  16.    4   5
  17.   / \   \
  18. 1   3   1

  19. Output: 9
  20. Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
复制代码

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. #     def __init__(self, val=0, left=None, right=None):
  4. #         self.val = val
  5. #         self.left = left
  6. #         self.right = right
  7. class Solution:
  8.     def rob(self, root: TreeNode) -> int:
  9.         result = self.helper(root)
  10.         return max(result)
  11.    
  12.     def helper(self, root: TreeNode) -> int:
  13.         if root == None:
  14.             return [0, 0]
  15.         result = [0, 0]
  16.         left = self.helper(root.left)
  17.         right = self.helper(root.right)
  18.         result[0] = max(left) + max(right)
  19.         result[1] = left[0] + right[0] + root.val
  20.         return result
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-6 09:49

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表