假设楼梯有N阶,一次只能爬一阶或两阶,问有几种爬楼梯的方法?
N=1, 1种
N=2, 2种
N=3, 3种
N=4, 5种
N=5, 8种
发现这好像斐波那契数列,后一个数等于前两个数之和。
F(N+2)=F(N+1)+F(N)
下面是c++代码:
#include <iostream>
using namespace std;
int step(int n)
{
if (n < 3)
{
return n;
}
else
{
return step(n-1)+step(n-2);
}
}
void main()
{
int n;
while (1)
{
cin >> n;
cout << step(n) << "种走法"<<endl;
}
system("pause");
}
网友评论