【问题标题】:Printing 1 to n using Fibonacci recursion [closed]使用斐波那契递归打印 1 到 n
【发布时间】:2015-02-09 22:10:51
【问题描述】:

我想在我的函数中打印从 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,IN 我的功能 我的意思是我想用递归算法打印它 这是我到目前为止的代码

#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;
    }
}

【问题讨论】:

  • “没有for,我无法做到”是什么意思?结合您的代码解释不能这个词。这段代码做错了什么?此外,如果 for 循环确实对您有用,请在此处与您的代码一起发布它,有人会指出差异的原因。
  • @barakmanos 我编辑了问题!
  • 如果你调用 "fibo(5, true)" 会打印什么?
  • @Aleph0 它什么也不打印!

标签: c++ algorithm recursion fibonacci


【解决方案1】:

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

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;        
}

DEMO

【讨论】:

  • 谢谢。但我并不担心一遍又一遍地重新计算斐波那契数列。我只想用递归算法来做到这一点。
  • 谢谢! :) 这是一个很好的建议
  • 我做了一个编辑,看看。
【解决方案2】:
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)
  • 如果父级没有打印,则从不打印(以避免在右分支的子左分支上打印)

【讨论】:

  • 谢谢,但我想在一个函数中完成
猜你喜欢
  • 2012-02-15
  • 2013-04-11
  • 2023-01-18
  • 2021-06-14
  • 2010-12-03
  • 2022-11-28
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多