题目:
写一个函数,输入n,求斐波那切数列的第n项。斐波那切数列的定义如下
0 n=0
f(n) = 1 n=1
f(n-1)+ f(n-2) n>1
思路:
直接进行递归会出现大量的重复计算,效率很低。因此使用循环的方法解决。
public class Solution {
public static long Fibonacci(int n){
if (n<=0) return 0;
if (n==1) return 1;
long before = 0;
long after = 1;
long ans=0;
for (int i = 1; i <n ; i++) {
ans = before+after;
before = after;
after = ans;
}
return ans;
}
}