走楼梯(stairs)
Background
Special for beginners, ^_^
Description
楼梯有 N级台阶,上楼可以一步上一阶,也可以一步上二阶。编一递推程序,计算共有多少种不同走法?
Input
一个整数 N(1 \le N \le 40)N(1≤N≤40),为台阶的级数。
Output
一个整数,为不同走法数。
Samples
输入数据 1
3
输出数据 1
3
题解:
只有两种情况;
(1) 从第n-1阶到第n阶
(2) 从第n-2阶到第n阶
#include <iostream>
using namespace std;
int stair(int n){
if (n>0){
if (1 == n){
return 1;
}
else if (2 == n){
return 2;
}
else{
return stair(n-1)+stair(n-2);
}
}
else
return 0;
}
int main(){
int n;
cin>>n;
cout<<stair(n)<<endl;
return 0;
}