写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项(即 F(N))。斐波那契数列的定义如下:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:1
示例 2:
输入:n = 5
输出:5
提示:
0 <= n <= 100
地址:https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof/
方法1:记录法,每次算都了记录下来,不重复算
方法2:移动数组法
滚动向前计算
func fib(n int) int {
if n<2{
return n
}
p,q,r:=0,0,1
for i:=2;i<=n;i++{
p=q
q=r
r=(p+q)%1000000007
}
return r
}