非递归:时间复杂度为O(n)
public class Solution {
public int Fibonacci(int n) {
int[] result = {0,1};
if(n <= 0)
return result[0];
if(n == 1)
return result[1];
int sum = 0;
for(int i = 2; i <= n; i++){
sum = result[0] + result[1];
result[0] = result[1];
result[1] = sum;
}
return sum;
}
}
本文介绍了一种非递归方式实现斐波那契数列的算法,该算法的时间复杂度为O(n),通过使用固定长度的数组来缓存中间结果,避免了递归带来的大量重复计算。

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



