题目:写一个函数,输入你n,求斐波那契数列的第n项
(1)C语言教科书上的递归解法
缺点:虽然直观,但时间效率低。(存在重复计算)
int f1(int n) {
if(n < 1) {
return 0;
}else if(n == 1 || n == 2) {
return 1;
}
return f1(n-1) + f1(n-2);
}
(2)递归的算法用循环实现
从下往上计算,时间复杂度O(n)
#include <iostream>
using namespace std;
long long Fibonacci(unsigned n)
{
int result[2] = {0,1};
if(n<2) return result[n];
long long fiboOne = 1;
long long fiboTwo = 0;
long fiboNew = 0; //最后结果
for(unsigned int i=2; i<=n; ++i)
{
fiboNew = fiboOne + fiboTwo;
fiboTwo = fiboOne;
fiboOne = fiboNew;
}
return fiboNew;
}
int main() {
long long n;
cin>>n;
cout << Fibonacci(n)<<endl;
return 0;
}
(3)用公式,时间复杂度O(logn)