斐波那契函数再总结--模板元编程

按照惯例先来一段代码:
先看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");

}

将时间转移到了编译期,如图所示:
这里写图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值