LeetCode 337. 打家劫舍 III

题目描述

🔥 337. 打家劫舍 III

思路分析

思路描述

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
func rob(root *TreeNode) int {
    result := robSub(root)
    return max(result[0], result[1])
}

func robSub(root *TreeNode) [2]int {
    if root == nil {
        return [2]int{0, 0}
    }
    
    leftResult := robSub(root.Left)
    rightResult := robSub(root.Right)
    
    // result[0] 表示不抢劫当前节点的最大金额
    // result[1] 表示抢劫当前节点的最大金额
    result := [2]int{}
    
    result[0] = max(leftResult[0], leftResult[1]) + max(rightResult[0], rightResult[1])
    result[1] = root.Val + leftResult[0] + rightResult[0]
    
    return result
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

🍏 点击查看 Java 题解

1
write your code here

相似题目

题目 难度 题解
打家劫舍 Medium  
打家劫舍 II Medium  
本文作者:
本文链接: https://hgnulb.github.io/blog/99943604
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!