回溯思想
已知楼梯有20阶台阶,上楼可以一步上1阶,也可以一步上2阶。请编写一个程序,计算总共有多少种不同的上楼梯的方法。
#include "stdio.h"
#define Max 20 //定义20个台阶的楼梯
int Steps[Max]={0}; //steps[i]等于1或者2,记录第i步登上的台阶数
int num=0; //记录上楼梯方案的数目
void Upstairs(int footStep,int count,int steps)
{
/*参数footstep为当前要登的台阶数,count是已经走过的阶数,steps 为走过的步数*/
int i;
if(count+footStep==Max){
/*已经走过的台阶数+当前要登的台阶数=20,得到一种上楼梯的方案*/
Steps[steps]=footStep;
for(i=0;i<=steps;i++)
{
printf("%d",Steps[i]);
}
printf("\n");
num++; //累计上楼梯的方案数
return;
}
if (count +footStep> Max)
{
//超过了楼梯的阶数,后续的解空间树不再搜索
return;
}
Steps[steps]=footStep; //记录当前上的楼梯的阶数
count=count + footStep;
steps++;
for(i=1;i<=2;i++)
{
Upstairs(i,count,steps);
}
}
void Upstairs_All(){
Upstairs(1,0,0);
Upstairs(2,0,0);
}
int main(){
Upstairs_All();
printf("共有%d种走法\n",num);
getche();
}