爬楼梯问题

给定楼梯阶数,可以往上走1阶,也可以往上走2阶。试问有多少种方法可以爬完楼梯,并且输出具体的爬梯方案。这里运用递归回溯的方法。代码如下:

#include<iostream>

using namespace std;

void climbStairs(int remainingSteps,int foot,int steps,int* process,int& count)
{
   if(remainingSteps-foot==0){// reach the top
         process[steps]=foot;
      for(int i=0;i<=steps;i++)
       {//output the foot in the process
           cout<<process[i]<<" ";
       }
       cout<<endl;
        ++count;
    }else if(remainingSteps-foot>0){// not reach the top
        process[steps]=foot;   //record the foot
        remainingSteps-=foot;   //update the remaining steps
        ++steps;                 //continue forward
      
        climbStairs(remainingSteps,1,steps,process,count);  //forward one foot
        climbStairs(remainingSteps,2,steps,process,count);  //forward two foot
    }else{  // over the top
        return;
    }

}
void climbStairsTwofoot(int n)
{
    int* process=new int[n];
    int count=0;
    climbStairs(n,1,0,process,count);
    climbStairs(n,2,0,process,count);
    cout<<count<<endl;  //output 10946
    delete [] process;
}
int main()
{
    climbStairsTwofoot(20);
    return 0;
}

用变量 remainingSteps表示当前剩余的步数,如果当前时刻再往前一步或者两步就到顶端了,则对方法总数count计数加1,而且要输出具体的到达方案,也就是在到达顶端位置之前经历过的那些步数。如果往前一步或者两步还没有到达顶端,则继续向前,可以爬一步,爬两步,都要进行。如果再继续往前不管是爬两步还是一步都超越顶端了则说明要么已经到达顶端要么方案不对,例如在倒数第一层你非要爬两步那岂不是到空中了吗,还是算了所以方案不成立也不计入总数,返回。

      当然如果此题不要求输出具体的爬楼梯方案则动态规划更能简洁地解决此问题,详情见LeetCode爬楼梯https://blog.csdn.net/Jeff_Winger/article/details/81386299

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值