Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9b79393

Browse files
committed
新增 0337.打家劫舍III.md Go解法
1 parent 28e3d95 commit 9b79393

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

‎problems/0337.打家劫舍III.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,35 @@ const rob = root => {
395395
};
396396
```
397397

398+
Go:
399+
```go
400+
// 打家劫舍III 动态规划
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+
```
398427

399428

400429

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /