题目概述
- 算法说明
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(F(0)=1,F(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2,n ∈ N*))。 - 测试用例
输入:
4
输出:
5
解析&参考答案
- 解析
方法1: 使用递归;
方法2: 使用循环; - 参考答案
vim jz02.go
package main
import "fmt"
func Fibonacci(n int) int {
if n == 0 || n == 1 {
return 1
}
return Fibonacci(n-1) + Fibonacci(n-2)
}
func FibonacciV2(n int) int {
if n == 0 || n == 1 {
return 1
}
a, b := 1, 1
for i := 2; i <= n; i++ {
a, b = b, a+b
}
return b
}
func main() {
n := 10
fmt.Println(Fibonacci(n))
fmt.Println(FibonacciV2(n))
}
vim jz02_.go
package main
import "testing"
var tests = []struct{ n, result int }{
{0, 1},
{1, 1},
{2, 2},
{4, 5},
}
func TestFibonacci(t *testing.T) {
for _, tt := range tests {
if actual := Fibonacci(tt.n); actual != tt.result {
t.Errorf("Fibonacci(%d)=%d, expected %d", tt.n, Fibonacci(tt.n), tt.result)
}
}
}
func TestFibonacciV2(t *testing.T) {
for _, tt := range tests {
if actual := FibonacciV2(tt.n); actual != tt.result {
t.Errorf("FibonacciV3(%d)=%d, expected %d", tt.n, FibonacciV2(tt.n), tt.result)
}
}
}
注意事项
- 递归的方法比较容易,但是递归次数很多的时候非常耗费内存,因此将递归转为循环后既高效有省内存。
说明
- 当前使用 go1.15.8
- 参考 牛客网--剑指offer
标题中jzn(n为具体数字)代表牛客网剑指offer系列第n号题目,例如 jz01 代表牛客网剑指offer中01号题目。
注意!!!
- 笔者最近在学习 golang,因此趁机通过数据结构和算法来进一步熟悉下go语言
- 当前算法主要来源于剑指 offer,后续会进一步补充 LeetCode 上重要算法,以及一些经典算法
- 此处答案仅为参考,不一定是最优解,欢迎感兴趣的读者在评论区提供更优解