LeetCode Weekly Contest 31
Q3 (7)
Give a map with height int, width int; tree []int; squirrel []int; nuts [][]int
Calculate the minimum steps for the squirrel to collect all the nuts and store them in the tree
func Abs(x int) int {
if x < 0 {
return -x
}
return x
}
func Dis(src[]int, tar[]int) int {
return Abs(src[0]-tar[0]) + Abs(src[1]-tar[1])
}
func minDistance(height int, width int, tree []int, squirrel []int, nuts [][]int) int {
moves := 0
disT := make([]int, 0)
for _, item := range nuts {
disT = append(disT, Dis(tree, item))
}
for index, _ := range nuts {
moves += 2*disT[index]
}
min := 0
for index, item := range nuts {
dis := Dis(squirrel, item)
if 0 == min || moves - disT[index] + dis < min {
min = moves - disT[index] + dis
}
}
return min
}
Subtree of Another Tree My SubmissionsBack To Contest
User Accepted: 798
User Tried: 912
Total Accepted: 813
Total Submissions: 2000
Difficulty: Easy
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func match(s *TreeNode, t *TreeNode) bool {
if nil == s && nil == t {
return true
}
if nil == s || nil == t {
return false
}
if s.Val != t.Val {
return false
}
if true == match(s.Left, t.Left) && true == match(s.Right, t.Right) {
return true
}
if true == match(s.Left, t.Right) && true == match(s.Right, t.Left) {
return true
}
return false
}
func dfs(s *TreeNode, t *TreeNode) bool {
if nil == s && nil != t {
return false
}
if s.Val == t.Val {
if true == match(s, t) {
return true
}
}
if true == dfs(s.Left, t) {
return true
}
if true == dfs(s.Right, t) {
return true
}
return false
}
func isSubtree(s *TreeNode, t *TreeNode) bool {
if nil == t {
return true
}
return dfs(s, t)
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。