使用斐波那契递归打印 1 到 n
Printing 1 to n using Fibonacci recursion
我想在我的函数中打印从 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;
}
请注意,这不仅在打印中有利,而且对计算本身也有好处(至少只要您多次调用该函数)。
除此之外,您还应考虑使用 long
或 double
作为返回类型,因为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;
}
演示
相关文章:
- 数组元素打印的递归方法
- 如何在C++中递归地按相反顺序打印集合
- 如何使用递归打印修改后的星号三角形图案
- 为什么我的递归函数按降序打印,然后按升序打印?
- 使用递归 c++ 打印模式
- 使用递归反转和打印出数组的内容
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- 使用类进行实现时,递归打印C++中的链表
- 如何使用递归打印最长公共子序列中涉及的字符串?
- 递归回溯打印长度为N的二进制数的所有组合,而不使用循环
- C++从递归函数中打印出奇怪的字符
- 使用递归打印所有递增子序列
- 二叉搜索树按级别递归C++打印节点
- 如果找不到解决方案,我如何留下递归循环,而不会打印任何东西
- 在1个功能中打印相反的三角递归C
- 使用递归打印输出
- 如何使用递归打印文本反驳
- 如何使用递归按从 1 到 n 的升序打印数字,其中 n 在该函数的参数中给出
- 如何打印递归 lambda 模板的名称
- 如何在递归函数中打印向量