Skip to content

Commit 90fece3

Browse files
Merge pull request #2782 from markwang1992/337-rob
337.打家劫舍III增加Go递归解法
2 parents d0af4f5 + fdae38c commit 90fece3

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

problems/0337.打家劫舍III.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,90 @@ class Solution:
388388

389389
### Go
390390

391+
暴力递归
392+
393+
```go
394+
/**
395+
* Definition for a binary tree node.
396+
* type TreeNode struct {
397+
* Val int
398+
* Left *TreeNode
399+
* Right *TreeNode
400+
* }
401+
*/
402+
func rob(root *TreeNode) int {
403+
if root == nil {
404+
return 0
405+
}
406+
if root.Left == nil && root.Right == nil {
407+
return root.Val
408+
}
409+
// 偷父节点
410+
val1 := root.Val
411+
if root.Left != nil {
412+
val1 += rob(root.Left.Left) + rob(root.Left.Right) // 跳过root->left,相当于不考虑左孩子了
413+
}
414+
if root.Right != nil {
415+
val1 += rob(root.Right.Left) + rob(root.Right.Right) // 跳过root->right,相当于不考虑右孩子了
416+
}
417+
// 不偷父节点
418+
val2 := rob(root.Left) + rob(root.Right) // 考虑root的左右孩子
419+
return max(val1, val2)
420+
}
421+
422+
func max(x, y int) int {
423+
if x > y {
424+
return x
425+
}
426+
return y
427+
}
428+
```
429+
430+
记忆化递推
431+
432+
```go
433+
/**
434+
* Definition for a binary tree node.
435+
* type TreeNode struct {
436+
* Val int
437+
* Left *TreeNode
438+
* Right *TreeNode
439+
* }
440+
*/
441+
var umap = make(map[*TreeNode]int)
442+
443+
func rob(root *TreeNode) int {
444+
if root == nil {
445+
return 0
446+
}
447+
if root.Left == nil && root.Right == nil {
448+
return root.Val
449+
}
450+
if val, ok := umap[root]; ok {
451+
return val // 如果umap里已经有记录则直接返回
452+
}
453+
// 偷父节点
454+
val1 := root.Val
455+
if root.Left != nil {
456+
val1 += rob(root.Left.Left) + rob(root.Left.Right) // 跳过root->left,相当于不考虑左孩子了
457+
}
458+
if root.Right != nil {
459+
val1 += rob(root.Right.Left) + rob(root.Right.Right) // 跳过root->right,相当于不考虑右孩子了
460+
}
461+
// 不偷父节点
462+
val2 := rob(root.Left) + rob(root.Right) // 考虑root的左右孩子
463+
umap[root] = max(val1, val2) // umap记录一下结果
464+
return max(val1, val2)
465+
}
466+
467+
func max(x, y int) int {
468+
if x > y {
469+
return x
470+
}
471+
return y
472+
}
473+
```
474+
391475
动态规划
392476

393477
```go

0 commit comments

Comments
 (0)