按照惯例先来一段代码:
先看feibo1
#include<iostream>
using namespace std;
int feibo1(int n)
{
int res;
int first = 1;
int second = 1;
if (n < 3)
{
return 1;
}
for(int i = 2; i < n; i++)
{
res = first + second;
first = second;
second = res;
}
return res;
}
int main()
{
int n;
while (cin >> n)
{
int res=feibo1(n);
cout << res << endl;
}
system("pause");
}
feibo1函数的时间复杂度为O(N),空间复杂度为O(1);
接下来看feibo2
int feibo2(int n)
{
if (n < 3)
{
return 1;
}
else
{
return feibo2(n - 1) + feibo2(n - 2);
}
}
int main()
{
int n;
while (cin >> n)
{
int res=feibo2(n);
cout << res << endl;
}
system("pause");
}
feibo2函数的时间复杂度为O(2^n)空间复杂度为O(N); 可以画一个递归树,每个节点都表示函数被调用一次
接下来看feibo3;
int feibo3(int n,int first=1,int second=1)
{
if (n < 3)
{
return 1;
}
if (n==3)
{
return second+first;
}
else
{
return feibo3( n-1,second,second + first);
}
}
int main()
{
int n;
while (cin >> n)
{
int res=feibo3(n);
cout << res << endl;
}
system("pause");
}
feibo3的时间复杂度为O(N)空间复杂度也为O(N);
接下来看模板元编程feibo5
//反复调用,函数等待,返回,浪费时间多
//模板元实现递归加速
//执行速度快,编译的时候慢,代码会增加
//把运行的时间节约在编译的时候
//递归加速,游戏优化,仅仅使用C11
template<int N>
struct data
{
//递归
enum { res = data<N - 1>::res + data<N - 2>::res };
};
template<>
struct data<1>
{
enum{ res = 1 };
};
template<>
struct data<2>
{
enum { res = 1 };
};
int main()
{
int n;
while (cin >> n)
{
cout << data<77>::res << endl;
}
system("pause");
}
将时间转移到了编译期,如图所示: