使用斐波那契递归打印 1 到 n

Printing 1 to n using Fibonacci recursion

本文关键字:打印 递归      更新时间:2023-10-16

我想在我的函数中打印从 1 到 n 的斐波那契级数。我知道我可以通过编写一个常规斐波那契并在 for 块中使用它来打印 1 到 N。喜欢这个:

#include <iostream>
using namespace std;
int fibo(int);
int main(){
    for (int i = 0; i < 5; i++)
        cout << fibo(5);
    system("pause");
    return 0;
}
int fibo(int n){
    if (n == 1 || n == 2)
        return 1;
    else
        return fibo(n - 1) + fibo(n - 2);
}

但我的问题是,没有for我就做不到,在我的函数中我的意思是我想用递归算法打印它这是我到目前为止的代码

#include <iostream>
using namespace std;
int fibo(int, bool);
int main(){
    fibo(5, false);
    system("pause");
    return 0;
}
int fibo(int n, bool IsPrinted){
    if (n == 1 || n == 2){
        if (!IsPrinted)
            cout << 1 << endl;
        return 1;
    }
    else{
        int temp = fibo(n - 1, IsPrinted) + fibo(n - 2, IsPrinted);
        if (!IsPrinted){
            cout << temp << endl;
            IsPrinted = true;
        }
        return temp;
    }
}
long fibo(int N, bool print) {
    long value = 0;
    if(1 == N)
        value = 1;
    if(1 < N)
        value = fibo(N-1, print) + fibo(N-2, false);
    if(print)
        std::cout << N << " => " << value << std::endl;
    return value;
}
int main(){
    fibo(5, true);
    return 0;
}

您应该意识到的是,对 fibo 函数的调用会形成一棵树。树的根是对main() fibo(5, true)的调用。由于您只想打印每个值一次,因此解决方案是决定仅在该树的最左侧分支上打印函数的值。规则很简单:

  • 切勿在右分支上打印(因此调用fibo(N-2, false)
  • 如果父分支未打印,则从不打印(以避免在右分支的子左分支上打印)

一个常见的解决方案是使用记忆:

int fibo(int n)
{
    static std::map<int,int> memo;
    auto it=memo.find(n);
    if(it!=std::end(memo))
    {
        return it->second;
    }
    int ret=1;
    if (n > 2)
    {
        ret = fibo(n - 1) + fibo(n - 2);
    }
    memo[n]=ret;
    return ret;
}

然后,您可以安全地循环访问输入参数,而无需一遍又一遍地重新计算值:

for(int i=0;i<20;++i)
{
    std::cout<<i<<"   "<<fibo(i)<<std::endl;
}

请注意,这不仅在打印中有利,而且对计算本身也有好处(至少只要您多次调用该函数)。

除此之外,您还应考虑使用 longdouble 作为返回类型,因为int会更快地溢出。


编辑

好的,在您编辑后,我不知道我的答案是否完全适合您的问题,但我认为这是一个很好的建议。

但我想这是另一个接近的快速替代方案:

int fibo(int n, bool first=true)
{
    int ret=0;
    if(n>2)
    {
        ret=fibo(n-1,false)+fibo(n-2,false);
    }
    else
    {
        ret=1;
    }
    if(first)
    {
        std::cout<<ret<<std::endl;
    }
    return ret;        
}

演示