上楼梯问题
【面试题】已知楼梯有20阶台阶,上楼可以一步上 1 阶,也可以一步上 2 阶,请编写一个函数计算一种有多少上楼梯的方式。
#include "stdio.h"
#include "math.h"
#define MAX_STEPS 20 /*定义20个台阶的楼梯*/
int Steps[MAX_STEPS] = {0}; /*Steps[i]等于1或者2,记录第i步登上的台阶数*/
int count = 0; /*记录上楼梯方案的数目*/
void Upstairs(int footStep, int haveUpstairedCount, int steps) {
/*参数footStep为当前要登的台阶数, haveUpstairedCount是已走过的阶数,steps为走过的步数*/
int i;
if (haveUpstairedCount + footStep == MAX_STEPS) {
/*已走过的台阶数+当前要登的台阶数=20,得到一种上楼梯的方案*/
Steps[steps] = footStep; /*记录下这一步登上的台阶数*/
for (i=0; i<=steps; i++) { /*输出这中上楼梯的方案*/
printf("%d ", Steps[i]);
}
getchar();
printf("\n");
count++;; /*累计上楼梯的方案数目*/
return;
}
if (haveUpstairedCount + footStep > MAX_STEPS) {
/*超过了楼梯的阶数,后续的解空间树不再探索*/
return;
}
Steps[steps] = footStep; /*记录当前上楼梯的阶数*/
haveUpstairedCount
= haveUpstairedCount + footStep; /*记录目前已走过的台阶数*/
steps++; /*步数加1*/
for (i=1; i<=2; i++) { /*递归探索后续的分支*/
Upstairs(i, haveUpstairedCount, steps);
}
}
void Upstairs_All() {
Upstairs(1,0,0); /*从第一步上1个台阶开始探索解空间树*/
Upstairs(2,0,0); /*从第一步上2个台阶开始探索解空间树*/
}
main() {
Upstairs_All();
printf("共有%d种走法\n",count); /*输出上楼梯方案的总数*/
getchar();
}