golang 斐波那契数列递归优化
package main import ( "fmt" "time" ) func main() { // 斐波那契数列 start := time.Now().UnixNano() nRes := fibo(30) fmt.Println(nRes) end := time.Now().UnixNano() fmt.Println("一般 Time:", end-start) // 斐波那契数列,备忘录 start2 := time.Now().UnixNano() var mapData = make(map[int]int, 0) nRes2 := fiboByRecord(mapData, 30) fmt.Println(nRes2) end2 := time.Now().UnixNano() fmt.Println("备忘录 Time:", end2-start2) // 斐波那契数列,loop start3 := time.Now().UnixNano() nRes3 := fiboByLoop(30) fmt.Println(nRes3) end3 := time.Now().UnixNano() fmt.Println("loop Time:", end3-start3) // 斐波那契数列,dp table start4 := time.Now().UnixNano() nRes4 := fiboByDp(30) fmt.Println(nRes4) end4 := time.Now().UnixNano() fmt.Println("dp table Time:", end4-start4) } // 一般递归 func fibo(n int) int { if n == 1 || n == 2 { return 1 } return fibo(n-1) + fibo(n-2) } // 利用备忘录递归 func fiboByRecord(mapData map[int]int, n int) int { if n == 1 || n == 2 { return 1 } if _, ok := mapData[n]; ok { return mapData[n] } mapData[n] = fiboByRecord(mapData, n-1) + fiboByRecord(mapData, n-2) return mapData[n] } // 非递归,使用循环 func fiboByLoop(n int) int { if n == 1 || n == 2 { return 1 } pre, cur := 1, 1 sum := 0 for i := 3; i <= n; i++ { sum = pre + cur pre = cur cur = sum } return cur } // 利用dp table func fiboByDp(n int) int { dp := make(map[int]int, n) if n <= 2 { return 1 } dp[1] = 1 dp[2] = 1 for i := 3; i <= n; i++ { dp[i] = dp[i-1] + dp[i-2] } return dp[n] }