我在 C++ 中学习了一个记住的斐波那契解法
#include<iostream>
using namespace std;
int F[51];
int fib(int n) {
if (n<=1)
{
return n;
}
if (F[n] != -1)
{
return F[n];
}
F[n] = fib(n-1) + fib(n-2);
return F[n];
}
int main()
{
for (int i=0; i<51; i++)
{
F[i] = -1;
}
int n;
cout<<"Give me an n: ";
cin>>n;
int result = fib(n);
cout<<result;
}
它工作正常,
$ g++ fibonacci.cpp
$ ./a.out
Give me an n: 10
55
尝试用python重现它
In [2]: %paste
F:List = [-1] * 50
def fib2(int:n) -> int:
if n < 2:
return n
if F[n] != -1:
return F[n]
F[n] = fib2(n-1) + fib2(n-2)
return F[n]
print(fib2(10))
尽管如此,它报告 RecursionError: maximum recursion depth exceeded in comparison
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-2-5e5ce2f4b1ad> in <module>
10 return F[n]
11
---> 12 print(fib2(10))
<ipython-input-2-5e5ce2f4b1ad> in fib2(int)
7 if F[n] != -1:
8 return F[n]
----> 9 F[n] = fib2(n-1) + fib2(n-2)
10 return F[n]
11
... last 1 frames repeated, from the frame below ...
<ipython-input-2-5e5ce2f4b1ad> in fib2(int)
7 if F[n] != -1:
8 return F[n]
----> 9 F[n] = fib2(n-1) + fib2(n-2)
10
仔细检查 python 解决方案是否与正在进行的解决方案具有相同的逻辑。
我的代码有什么问题。
慕田峪7331174
心有法竹
相关分类