File tree Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Original file line number Diff line number Diff line change @@ -388,6 +388,90 @@ class Solution:
388
388
389
389
### Go
390
390
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
+
391
475
动态规划
392
476
393
477
``` go
You can’t perform that action at this time.
0 commit comments