高效斐波那契数列解法

来源:互联网 发布:论文抄袭检测软件 编辑:程序博客网 时间:2024/06/06 15:43

教科书上写递归算法的时候,没有考虑效率。

这里的代码考虑了将已经计算过的数据记忆下来,使用的时候直接查表。速度就快很多。

这样的时间复杂度是O(n),空间复杂度也是O(n)。

看代码:

#include <cstdlib>  #include <iostream>  using namespace std;const int MAX = 100;__int64 fac[MAX] = {0};__int64 fact(int n){     if(n <= 1)         return n;     if(fac[n] > 0)         return fac[n];           fac[n] = fact(n - 1) + fact(n - 2);     return fac[n];}        int main(int argc, char *argv[])  {      int value;    cin >> value;        cout << fact(value) << endl;        system("PAUSE");      return EXIT_SUCCESS;  }  


代码cp 了别人的。意思很明确很容易理解。

原创粉丝点击