从楼上走到楼下共有h个台阶,每一步有三种走法,走1个台阶,2个台阶和3个台阶,问走完台阶可以有多少种走法?
要求:用递归函数来编程。
下一个楼梯只有一种下法,下两个楼梯有两种下法,下三个楼梯有四种下法,其余的情况均可由以上三种情况组合而成。
#include <iostream>
using namespace std;
int steps(int n){
if(n == 3){
return 4;
}
if(n ==2){
return 2;
}
if(n == 1){
return 1;
}
else return steps(n-1)+steps(n-2)+steps(n-3);
}
int main(){
int h;
cout<<"how many stars: ";
cin>>h;
cout<<"there are "<<steps(h)<<" solutions"<<endl;
return 0;
}