Leetcode 337. 打家劫舍 III

心路历程:

还是经典的动态规划题,建模思路:

状态:第i个房间;j偷或者不偷

候选动作:偷 或者不偷

返回值:当前状态获得的最大金额

注意的点:

1、当计算当前结点被偷时,注意node.val不要加重复了

2、objective对象也是hashable的,可以@cache处理

解法:动态规划

python 复制代码
# Definition for a binary tree node.
# 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: Optional[TreeNode]) -> int:

        @cache
        def dp(node, j):
            # if not node: return 0
            if j == 0: 
                res1, res2 = 0, 0
                if node.left: res1 = max(dp(node.left, 1), dp(node.left, 0))
                if node.right: res2 = max(dp(node.right, 1), dp(node.right, 0))
                return res1 + res2
            else:  # 这块的node.val不要加重复了!!!
                res1, res2 = 0, 0
                if node.left: res1 = dp(node.left, 0)
                if node.right: res2 = dp(node.right, 0)
                return res1 + res2 + node.val
        return max(dp(root, 1), dp(root, 0))
相关推荐
2301_807367194 分钟前
C++中的解释器模式变体
开发语言·c++·算法
愣头不青18 分钟前
617.合并二叉树
java·算法
MIUMIUKK1 小时前
双指针三大例题
算法
灵感__idea1 小时前
Hello 算法:复杂问题的应对策略
前端·javascript·算法
2301_819414302 小时前
C++与区块链智能合约
开发语言·c++·算法
Zaly.2 小时前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵
算法·leetcode·矩阵
做怪小疯子2 小时前
蚂蚁暑期 319 笔试
算法·职场和发展
计算机安禾2 小时前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现
c语言·开发语言·数据结构·c++·算法·链表·蓝桥杯
啊哦呃咦唔鱼2 小时前
LeetCode hot100-73 矩阵置零
算法
阿贵---3 小时前
C++构建缓存加速
开发语言·c++·算法