数据结构之回溯思想

回溯思想


已知楼梯有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();

}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值