写一个函数,输入 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
方法1:动态规划
public class Fib {
public int fib(int n) {
if (n == 0){
return 0;
}
if (n == 1){
return 1;
}
int[] result = new int[n + 1];
result[0] = 0;
result[1] = 1;
for (int i = 2; i < result.length; i++) {
result[i] = result[i-1] + result[i-2];
result[i] = result[i]%1000000007;
}
return result[n];
}
}
方法2:递归,但是需要记录每次的值,以防重复计算
例如
f(5) = f(4) + f(3)
f(4) = f(3) + f(2)
因此计算 f(5) 时会计算两次 f(3),产生重复计算
需要建一个数组,保存每次计算的结果,如果这个数不为0,则直接返回,否则计算后存入对应的位置
注意这个数组需要用 static 修饰,以实现计算过的结果在所有测试样例中共享。
class Solution {
static int[] temp = new int[101];
public int fib(int n) {
if (n < 2){
temp[n] = n;
return n;
}
if (temp[n] != 0){
return temp[n];
}
temp[n] = fib(n-1) + fib(n-2);
temp[n] = temp[n]%1000000007;
return temp[n];
}
}