题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。
n≤39
递归写法
public int Fibonacci(int n) {
if (n == 0 || n == 1) {
return n;
}
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
非递归写法
//考虑到第 i 项只与第 i-1 和第 i-2 项有关,因此只需要存储前两项的值就能求解第 i 项
public int Fibonacci(int n) {
if (n <= 1) {
return n;
}
int l = 0;
int r = 1;
int temp = 0;
//用循环保存i-1和i-2项
// l r temp
// l r temp
for (int i = 2; i <= n; i++) {
temp = l + r;
l = r;
r = temp;
}
return temp;
}
本文介绍了一种常见的数学序列——斐波那契数列,并提供了两种不同的编程实现方式:递归方法和非递归方法。递归方法简洁但效率较低,而非递归方法则更加高效。
7531

被折叠的 条评论
为什么被折叠?



