使用動態規劃返回斐波那契數列中第 n 個數的 Golang 程式
在本文中,我們將編寫 Go 語言程式,使用動態規劃返回斐波那契數列中的第 n 個數。這是一種透過將複雜問題分解成更小的子問題來解決複雜問題的技術。
記憶化是將函式呼叫的輸出儲存在某些資料結構中的過程,這樣下次呼叫時就不需要再次計算輸出,它可以使用該值進行計算,從而減少執行時間。
語法
func make ([] type, size, capacity)
Go 語言中的make函式用於建立陣列/對映,它接受要建立的變數型別、大小和容量作為引數。
演算法
此程式匯入 main 和 fmt 包。
建立一個名為 fibo(n int) int 的函式,該函式接受整數 n 作為輸入引數並返回所需的斐波那契數。
使用 make 作為內建函式建立一個大小為 n+1 的切片 fib 來儲存斐波那契數。
設定第 0 個和第 1 個斐波那契數。
在此步驟中,使用 for 迴圈從 2 迭代到 n,在每次迭代中計算第 i 個斐波那契數。
迴圈終止後,返回 fib[n] 作為輸出。
建立一個 main 函式,在其中設定要計算其斐波那契值的第 n 個數。
然後,使用 n 作為引數呼叫 fibo() 函式來計算輸出。
使用 fmt 包中的 printf 函式在控制檯上列印輸出。
示例 1
在此示例中,我們將編寫一個 Golang 程式,透過將前兩個斐波那契數相加來找到第 n 個斐波那契數以獲得當前數,並將其儲存在使用 make 函式建立的切片中。
package main import "fmt" func fibo(n int) int { fib := make([]int, n+1) fib[0] = 0 fib[1] = 1 for i := 2; i <= n; i++ { fib[i] = fib[i-1] + fib[i-2] } return fib[n] } func main() { n := 6 output := fibo(n) fmt.Printf("The %dth number in this Fibonacci sequence is: %d\n", n, output) }
輸出
The 6th number in this Fibonacci sequence is : 8
示例 2
在此示例中,我們將編寫一個 Golang 程式,透過使用儲存使用遞迴計算的斐波那契數的對映來返回斐波那契數列中的第 n 個數。
package main import "fmt" var store map[int]int func fibo(n int) int { if val, ok := store[n]; ok { return val } if n == 0 { store[n] = 0 return 0 } else if n == 1 { store[n] = 1 return 1 } fib := fibo(n-1) + fibo(n-2) store[n] = fib return fib } func main() { n := 8 store = make(map[int]int) output := fibo(n) fmt.Printf("The %dth number in the Fibonacci sequence is: %d\n", n, output) }
輸出
The 8th number in the Fibonacci sequence is: 21
結論
我們使用兩種方法編譯並執行了使用動態規劃返回斐波那契數列中第 n 個數的程式。在第一種方法中,我們使用了動態規劃,在第二種方法中,我們使用了帶動態規劃的記憶化。
廣告