Leetcode.337.打家劫舍III

原题链接:https://leetcode-cn.com/problems/house-robber-iii/
解题思路:
因为所有的房屋按照二叉树的结构排布。不能同时抢相邻层的房间。
利用递归的思想求解这个题。
如果小偷偷了第i层,那么就不可以抢第i+1层。
建立一个有两个元素的列表,第一个元素存储不抢这一层的获得的最高金额。第二个元素存储抢这一层获得的最高金额。

# 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 treerob(root):
            res = [0]*2
            if not root:
                return res
            left = treerob(root.left)  # 入口为root.left时,获得最大金额
            right = treerob(root.right)  # 入口为root.right时,获得最大金额
            res[0] = max(left[0],left[1])+max(right[0],right[1])
            res[1] = root.val + left[0] + right[0]
            return res
        res = treerob(root)
        return max(res)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值