给定楼梯阶数,可以往上走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