【解题思路】
首先想到是就是递归,超出时间限制。因为递归中有很多重复的计算,比如计算f(5) = f(4) + f(3),需要计算f(4) = f(3) + f(2) 、f(3) = f(2) + f(1) 、f(2) = f(1) + f(0)、f(2) = f(1) + f(0)和f(3) = f(2) + f(1)、f(2) = f(1) + f(0)。
使用一个数组ans[ ]记录已经计算过的值,不再重复运算,可以大大节省时间开销。
class Solution {
public int fib(int n) {
if(n == 0) return 0;
int[] ans = new int[n+1];
ans[0] = 0;
ans[1] = 1;
int MOD = 1000000007;
for(int i = 2; i < n+1; i++)
{
ans[i] = (ans[i-1] + ans[i-2]) % MOD;
}
return ans[n];
}
}