Skip to content

Commit 99d28fc

Browse files
committed
337.打家劫舍Ⅲ 增加go的解法 树形DP
1 parent f88678d commit 99d28fc

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

problems/0337.打家劫舍III.md

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

371+
Go:
372+
373+
树形DP
374+
375+
```go
376+
/**
377+
* Definition for a binary tree node.
378+
* type TreeNode struct {
379+
* Val int
380+
* Left *TreeNode
381+
* Right *TreeNode
382+
* }
383+
*/
384+
func rob(root *TreeNode) int {
385+
return max(robTree(root))
386+
}
387+
func robTree(root *TreeNode)(int,int){
388+
if root==nil{
389+
return 0,0
390+
}
391+
//获取左节点的偷的值与不偷的值
392+
left0,left1:=robTree(root.Left)
393+
//获取右节点的偷的值与不偷的值
394+
right0,right1:=robTree(root.Right)
395+
//
396+
val1:=root.Val
397+
val1+=left1+right1
398+
//不偷
399+
val2:=0
400+
val2+=max(left0,left1)+max(right0,right1)
401+
return val1,val2
402+
}
403+
func max(a,b int)int{
404+
if a>b{
405+
return a
406+
}
407+
return b
408+
}
409+
```
410+
411+
412+
371413
JavaScript:
372414

373415
> 动态规划

0 commit comments

Comments
 (0)