go实现斐波那契数

LeetCode-509

 

package main

import "fmt"

func fib(n int) int {
	if n < 2 {
		return n
	}
	nums := make([]int, n+1)
	nums[0], nums[1] = 1, 1
	for i := 2; i < n; i++ {
		// nums[i] = (nums[i-1] + nums[i-2]) % 1000000007
		nums[i] = nums[i-1] + nums[i-2]
	}
	return nums[n]
}

func fib01(n int) int {
	if n < 2 {
		return 2
	}
	return fib01(n-1) + fib(n-2)
}

func main() {
	var n int
	fmt.Scanln(&n)
	fmt.Println(fib(n))
	fmt.Println("the fib01 is ", fib01(n))

}

  

posted @ 2021-04-04 23:52  qstudy  阅读(109)  评论(0编辑  收藏  举报