算法inGolang:Recursion(递归)递归算法场景:在套娃中找到宝石可以这样做while没找到:if当前项is宝石:return宝石elseif当前项is套娃:打开这个套娃if当前项is宝石:return宝石elsei
~/Code/go via 🐹 v1.20.3 via 🅒 base
➜ mcd recursion_demo
Code/go/recursion_demo via 🐹 v1.20.3 via 🅒 base
➜ go mod init recursion_demo
go: creating new go.mod: module recursion_demo
Code/go/recursion_demo via 🐹 v1.20.3 via 🅒 base
➜ c
Code/go/recursion_demo via 🐹 v1.20.3 via 🅒 base
➜
代码:
package main
import "fmt"
func main() {
doll := Item{
ID: 1,
Type: "doll",
Child: &Item{
ID: 2,
Type: "doll",
Child: &Item{
ID: 3,
Type: "doll",
Child: &Item{
ID: 4,
Type: "diamond",
Child: nil,
},
},
},
}
diamond := findDiamond(doll)
fmt.Printf("Item %d is diamond\n", diamond.ID)
}
func findDiamond(item Item) Item {
if item.IsDoll() {
return findDiamond(*item.Child)
} else {
return item
}
}
type Item struct {
ID int
Type string
Child *Item
}
type ItemClassifier interface {
IsDoll() bool
}
func (it *Item) IsDoll() bool {
if it.Type == "doll" {
return true
}
return false
}
运行
Code/go/recursion_demo via 🐹 v1.20.3 via 🅒 base
➜ go run .
Item 4 is diamond
Code/go/recursion_demo via 🐹 v1.20.3 via 🅒 base
➜
优化
package main
import "fmt"
func main() {
doll := Item{
ID: 1,
Type: "doll",
Child: &Item{
ID: 2,
Type: "doll",
Child: &Item{
ID: 3,
Type: "doll",
Child: &Item{
ID: 4,
Type: "diamond",
Child: nil,
},
},
},
}
diamond := findDiamond(doll)
fmt.Printf("Item %d is diamond\n", diamond.ID)
}
func findDiamond(item Item) Item {
if item.IsDoll() {
return findDiamond(*item.Child)
} else {
return item
}
}
type Item struct {
ID int
Type string
Child *Item
}
type ItemClassifier interface {
IsDoll() bool
}
func (it *Item) IsDoll() bool {
return it.Type == "doll"
}
这段代码的主要功能是查找一个嵌套的Item结构体中的钻石,并输出其ID。优化的话可以考虑以下几点:
下面是优化后的代码:
package main
import "fmt"
func main() {
doll := createItemChain()
diamond := findDiamond(doll)
fmt.Printf("Item %d is diamond\n", diamond.ID)
}
func createItemChain() *Item {
doll := &Item{
ID: 1,
Type: "doll",
}
doll.Child = &Item{
ID: 2,
Type: "doll",
}
doll.Child.Child = &Item{
ID: 3,
Type: "doll",
}
doll.Child.Child.Child = &Item{
ID: 4,
Type: "diamond",
}
return doll
}
func findDiamond(item *Item) *Item {
if item.IsDoll() {
return findDiamond(item.Child)
}
return item
}
type Item struct {
ID int
Type string
Child *Item
}
func (it *Item) IsDoll() bool {
return it.Type == "doll"
}
优化说明:
findDiamond
函数的参数和返回值改为 *Item
类型,以便避免不必要的内存拷贝。Item
链的代码提取到一个单独的函数 createItemChain
中,使代码更清晰。createItemChain
函数中使用指针来创建 Item
对象,以避免在函数间传递大量的数据。findDiamond
函数,使其接受 *Item
参数,以避免在递归调用时进行不必要的解引用。findDiamond
函数的递归调用,将 item.Child
直接传递给 findDiamond
,而不是解引用再传递。ItemClassifier
接口的定义移除,因为在当前代码中没有使用到它。如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!