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 b64e348

Browse files
committed
Add Go into 337.打家劫舍III.md
1 parent 7bb935c commit b64e348

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,41 @@ class Solution:
368368
return (val1, val2)
369369
```
370370

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+
371406
JavaScript:
372407

373408
> 动态规划

0 commit comments

Comments
(0)

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