25.下列递归表达式的时间复杂度是多少()。
T(n)函数递归调用规律一致
变成了25题了。
具体题目:
求解斐波那契数列的F(n)有两种常用算法:递归算法和非递归算法。试分析两种算法的时间复杂度。
1.递归算法
#include<iostream>
using namespace std;
long Fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return Fibonacci(n - 1) + Fibonacci(n-2);
}
int main() {
cout << "Enter an integer number:" << endl;
int N;
cin >> N;
cout << Fibonacci(N) << endl;
system("pause");
return 0;
}
时间复杂度分析:
求解F(n),必须先计算F(n-1)和F(n-2),计算F(n-1)和F(n-2),又必须先计算F(n-3)和F(n-4)。。。。。。以此类推,直至必须先计算F(1)和F(0),然后逆推得到F(n-1)和F(n-2)的结果,从而得到F(n)要计算很多重复的值,在时间上造成了很大的浪费,算法的时间复杂度随着N的增大呈现指数增长,时间的复杂度为O(2^n),即2的n次方
2.非递归算法
#include<iostream>
using namespace std;
long Fibonacci(int n) {
if (n <= 2)
return 1;
else {
long num1 = 1;
long num2 = 1;
for (int i = 2;i < n - 1;i++) {
num2 = num1 + num2;
num1 = num2 - num1;
}
return num1 + num2;
}
}
int main() {
cout << "Enter an integer number:" << endl;
int N;
cin >> N;
cout << Fibonacci(N) << endl;
system("pause");
return 0;
}
时间复杂度分析:
从n(>2)开始计算,用F(n-1)和F(n-2)两个数相加求出结果,这样就避免了大量的重复计算,它的效率比递归算法快得多,算法的时间复杂度与n成正比,即算法的时间复杂度为O(n).
另一种方法:
https://blog.csdn.net/beautyofmath/article/details/48184331