题目:
树老师爬楼梯,他可以每次走1级或者2级,输入楼梯的级数,求不同的走法数。
例如:楼梯一共有3级,他可以每次都走一级,或者第一次走一级,
第二次走两级,也可以第一次走两级,第二次走一级,一共3种方法。
解法:
用递归将问题分解为规模更小的子问题进行求解
n 级台阶的走法 = (先走一步)n-1级台阶的走法 + (先走两步)n-2级台阶的走法。
f(n) = f(n-1) + f(n-2)
#include<iostream>
using namespace std;
int N;
int stairs(int n)
{
if( n<0 ){
return 0;
}else if( n==0 ){
return 1;
}
return stairs(n-1) + stairs(n-2);
}
int main()
{
while( cin>>N ){
cout<< stairs(N) << endl;
}
return 0;
}