File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -368,6 +368,41 @@ class Solution:
368
368
return (val1, val2)
369
369
```
370
370
371
+ Go:
372
+
373
+ > 动态规划
374
+
375
+ ``` go
376
+ func rob (root *TreeNode ) int {
377
+ res := robTree (root)
378
+ return max (res[0 ], res[1 ])
379
+ }
380
+
381
+ func max (a , b int ) int {
382
+ if a > b {
383
+ return a
384
+ }
385
+ return b
386
+ }
387
+
388
+ func robTree (cur *TreeNode ) []int {
389
+ if cur == nil {
390
+ return []int {0 , 0 }
391
+ }
392
+ // 后序遍历
393
+ left := robTree (cur.Left )
394
+ right := robTree (cur.Right )
395
+
396
+ // 考虑去偷当前的屋子
397
+ robCur := cur.Val + left[0 ] + right[0 ]
398
+ // 考虑不去偷当前的屋子
399
+ notRobCur := max (left[0 ], left[1 ]) + max (right[0 ], right[1 ])
400
+
401
+ // 注意顺序:0:不偷,1:去偷
402
+ return []int {notRobCur, robCur}
403
+ }
404
+ ```
405
+
371
406
JavaScript:
372
407
373
408
> 动态规划
You can’t perform that action at this time.
0 commit comments