递归斐波那契,打印出第一个斐波那契元素 [英] recursive fibonacci that prints n first fibonacci element
问题描述
嗨朋友们。
我想写一个递归函数将N个第一个元素打印到递归函数中。
但我不知道怎么做?
例如召回Fib(8),然后它应该打印0 1 1 2 3 5 8 13
谢谢。
Hi friends.
I want to write a recursive function to print N first element into the recursive function.
But i dont know how do it?
for example recalling Fib(8), then it should print 0 1 1 2 3 5 8 13
thanks.
推荐答案
如果你尝试用递归的方法解决
这样的功能:
If you try to solve with recursive approch
with a fucnction like this :
int F(int n)
{
if(n==0 || n==1){
cout<<1<<" ";
return 1;
}
int RET=F(n-2)+F(n-1);
cout<<RET<<" ";
}
这个函数是O(2 ^ N)
i建议你Dyanmic approch
首先尝试填写表格F []
this Function would be O(2^N)
i suggest you Dyanmic approch
First try to fill a Table of F[]
int F[maxn];
F[0]=F[1]=1;
for(int i=2;i<maxn;i++)>
F[i]=F[i-1]+F[i-2];
现在你已经在时间顺序为O(N)的数组中保存Fibonacci序列
now you have Fibonacci Sequenced Saved in An Array with The Time Order O(N)
如何定义递归函数在C / C ++中:
How to define a recursive function in C/C++:
int foo(int n) {
int result = 0;
// step 0: pin down the result value(s) for starting the recursion
const int first_value = 1;
// step 1: test if you're at the root of the recursion
if (0 == n)
result = first_value;
else {
// step 2: determine previous result through recursion
int previous_result = foo(n-1);
// step 3: determine result from previous result
result = n*previous_result;
}
return result;
}
注意:
- 如果递归需要多于1个值来计算,则步骤0可能需要多个值下一个。
- 如果您有多个起始值,第1步可能需要多次检查
- 奖励提示:您应该添加额外的支票(例如 if(n< 0)
)以确保你有一个有效的参数,并且不会意外地遇到无限循环。
阅读并理解注释以使此示例代码适应斐波那契序列。我不会那样做,因为它闻起来有作业,如果我为你做的话,我无法帮你学习。
Notes:
- step 0 may require more than one value if your recursion requires more than 1 value to calculate the next one.
- step 1 may require multiple checks if you have multiple starting values
- bonus hint: you should add an additional check ( e. g. if (n < 0)
) to make sure you have a valid argument and won't accidentally run into an endless loop.
Read and understand the notes to adapt this example code for the fibonacci sequence. I won't do that for you since it smells of homework, and I can't help you learn if I do it for you.
这篇关于递归斐波那契,打印出第一个斐波那契元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!