数组02--斐波那契数列-jz07

题目概述

  • 算法说明
    大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1,n≤39)。
  • 测试用例
    输入:
    4
    输出:
    3

解析&参考答案

  • 解析
    方法1: 使用递归;
    方法2: 使用循环;
  • 参考答案
vim jz02.go
package main

import "fmt"

func Fibonacci(n int) int {
if n == 0 {
return 0
}
if n == 1 {
return 1
}
return Fibonacci(n-1) + Fibonacci(n-2)
}

func FibonacciV2(n int) int {
if n == 0 || n == 1 {
return n
}
if n == 1 {
return 1
}
a, b := 0, 1
for i := 2; i <= n; i++ {
a, b = b, a+b
}
return b
}

func main() {
n := 4
result := Fibonacci(n)
fmt.Println(result)
}

vim jz02_.go
package main

import "testing"

var tests = []struct{ n, result int }{
{0, 0},
{1, 1},
{2, 1},
{4, 3},
}

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)
}
}
}

注意事项

  1. 递归的方法比较容易,但是递归次数很多的时候非常耗费内存,因此将递归转为循环后既高效有省内存。

说明

  1. 当前使用 go1.15.8
  2. 参考​​牛客网--剑指offer​​ 标题中jzn(n为具体数字)代表牛客网剑指offer系列第n号题目,例如 jz01 代表牛客网剑指offer中01号题目。

注意!!!

  • 笔者最近在学习 golang,因此趁机通过数据结构和算法来进一步熟悉下go语言
  • 当前算法主要来源于剑指 offer,后续会进一步补充 LeetCode 上重要算法,以及一些经典算法
  • 此处答案仅为参考,不一定是最优解,欢迎感兴趣的读者在评论区提供更优解