您的位置:首页 > Web前端

斐波那契数列第n个数

2016-04-12 15:48 239 查看
题目描述:输出斐波那契数列第n个数,第一个为1,第二个为1,第三个为2。。。

描述:

可以使用循环或者递归来实现,但是使用递归时间会消耗较多。

代码如下:

1. 递归

<span style="font-size:14px;">class Solution {
public:
int Fibonacci(int n) {
if(n<=0)
return NULL;
if(n==1)
return 1;
if(n==2)
return 1;
return Fibonacci(n-1)+Fibonacci(n-2);
}
};
</span>2.循环
<span style="font-size:14px;">class Solution {
public:
int Fibonacci(int n) {
if(n<=0)
return NULL;
if(n==1)
return 1;
if(n==2)
return 1;
int len1=1,len2=1,len3=0;
for(int i=2;i<n;i++){
len3=len1+len2;
len1=len2;
len2=len3;
}
return len3;
}
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  剑指offer 递归