版权声明:转载请联系 :[email protected] https://blog.csdn.net/weixin_40928253/article/details/85254132
斐波那契数列
题目描述:
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
###解题思路:
整体思路:考虑负数,大数,算法的复杂度,空间的浪费
public class Solution {
public int Fibonacci(int n) {
//使用迭代法,用fn1和fn2保存计算过程中的结果,并复用起来
int fn1 = 1;
int fn2 = 1;
//考虑出错的情况
if (n <= 0)
return 0;
//第一个和第二个直接返回
if (n == 1|| n == 2)
return 1;
//当n>= 3时,说明用迭代法算出结果
while (n -- > 2){
fn1 += fn2;
fn2 = fn1 - fn2;
}
return fn1;
}
}