Merge pull request #2782 from markwang1992/337-rob

337.打家劫舍III增加Go递归解法
This commit is contained in:
程序员Carl
2024-11-06 10:29:43 +08:00
committed by GitHub

View File

@ -388,6 +388,90 @@ class Solution:
### Go
暴力递归
```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rob(root *TreeNode) int {
if root == nil {
return 0
}
if root.Left == nil && root.Right == nil {
return root.Val
}
// 偷父节点
val1 := root.Val
if root.Left != nil {
val1 += rob(root.Left.Left) + rob(root.Left.Right) // 跳过root->left相当于不考虑左孩子了
}
if root.Right != nil {
val1 += rob(root.Right.Left) + rob(root.Right.Right) // 跳过root->right相当于不考虑右孩子了
}
// 不偷父节点
val2 := rob(root.Left) + rob(root.Right) // 考虑root的左右孩子
return max(val1, val2)
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
```
记忆化递推
```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var umap = make(map[*TreeNode]int)
func rob(root *TreeNode) int {
if root == nil {
return 0
}
if root.Left == nil && root.Right == nil {
return root.Val
}
if val, ok := umap[root]; ok {
return val // 如果umap里已经有记录则直接返回
}
// 偷父节点
val1 := root.Val
if root.Left != nil {
val1 += rob(root.Left.Left) + rob(root.Left.Right) // 跳过root->left相当于不考虑左孩子了
}
if root.Right != nil {
val1 += rob(root.Right.Left) + rob(root.Right.Right) // 跳过root->right相当于不考虑右孩子了
}
// 不偷父节点
val2 := rob(root.Left) + rob(root.Right) // 考虑root的左右孩子
umap[root] = max(val1, val2) // umap记录一下结果
return max(val1, val2)
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
```
动态规划
```go