We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 28e3d95 commit 9b79393Copy full SHA for 9b79393
problems/0337.打家劫舍III.md
@@ -395,6 +395,35 @@ const rob = root => {
395
};
396
```
397
398
+Go:
399
+```go
400
+// 打家劫舍Ⅲ 动态规划
401
+// 时间复杂度O(n) 空间复杂度O(logn)
402
+func rob(root *TreeNode) int {
403
+ dp := traversal(root)
404
+ return max(dp[0], dp[1])
405
+}
406
+
407
+func traversal(cur *TreeNode) []int {
408
+ if cur == nil {
409
+ return []int{0, 0}
410
+ }
411
412
+ dpL := traversal(cur.Left)
413
+ dpR := traversal(cur.Right)
414
415
+ val1 := cur.Val + dpL[0] + dpR[0] // 偷盗当前节点
416
+ val2 := max(dpL[0], dpL[1]) + max(dpR[0], dpR[1]) // 不偷盗当前节点
417
+ return []int{val2, val1}
418
419
420
+func max(a, b int) int {
421
+ if a > b {
422
+ return a
423
424
+ return b
425
426
+```
427
428
429
0 commit comments