mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 21:10:58 +08:00
337.打家劫舍Ⅲ 增加go的解法 树形DP
This commit is contained in:
@ -368,6 +368,48 @@ class Solution:
|
||||
return (val1, val2)
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
树形DP
|
||||
|
||||
```go
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* type TreeNode struct {
|
||||
* Val int
|
||||
* Left *TreeNode
|
||||
* Right *TreeNode
|
||||
* }
|
||||
*/
|
||||
func rob(root *TreeNode) int {
|
||||
return max(robTree(root))
|
||||
}
|
||||
func robTree(root *TreeNode)(int,int){
|
||||
if root==nil{
|
||||
return 0,0
|
||||
}
|
||||
//获取左节点的偷的值与不偷的值
|
||||
left0,left1:=robTree(root.Left)
|
||||
//获取右节点的偷的值与不偷的值
|
||||
right0,right1:=robTree(root.Right)
|
||||
//偷
|
||||
val1:=root.Val
|
||||
val1+=left1+right1
|
||||
//不偷
|
||||
val2:=0
|
||||
val2+=max(left0,left1)+max(right0,right1)
|
||||
return val1,val2
|
||||
}
|
||||
func max(a,b int)int{
|
||||
if a>b{
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
JavaScript:
|
||||
|
||||
> 动态规划
|
||||
|
Reference in New Issue
Block a user