思路1 [递归]
直接使用递归去思考的话,会发现时间复杂度太高了。
因此可以用使用Map图去代替一个备忘录,记录0~n-1对应的斐波那契数,
在后面需要使用的时候,直接调出来即可,而不用重新计算。
public int fib(int n) {
return fib(n,new HashMap());
}
public static int fib(int n,Map<Integer,Integer> map)
{
if(n<2) return n;
if(map.containsKey(n))
return map.get(n);
int first =fib(n-1,map)%1000000007;
map.put(n-1,first);
int second = fib(n-2,map)%1000000007;
map.put(n-2,second);
int res=(first+second)%1000000007;
map.put(n,res);
return res;
}
思路二 【非递归】
实际上递归函数的时间复杂度会比非递归函数的时间复杂度高上很多;
因此我们不使用递归函数,用一个普通的循环函数即可。
public int fib(int n) {
if(n<2) return n;
int pre=0;
int last =1;
int sum =0;
for(int i=1;i<n;i++)
{
sum = (pre+last)%1000000007;
pre= last;
last = sum;
}
return sum;
}