程序设计爬楼梯问题
A child is running up a staircase with N steps, and can hop 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run up to the stairs? You need to return number of possible ways W.
一个孩子正在上楼梯, 步伐为N步 ,可以一次跳1步, 2步或3步。 实施一种方法来计算孩子可以上楼梯的多少种方式 ? 您需要返回可能的方式W的数量。
Input format: Line 1: Integer N (No. of steps)
输入格式:第1行:整数N(步数)
Output Format: Line 1: Integer W i.e. Number of possible ways
输出格式:第1行:整数W,即可能的方式数
Constraint: (1 <= N <= 30)
约束: (1 <= N <= 30)
Sample Input 1: 4
样本输入1: 4
Sample Output: 7
样本输出: 7
Explanation:
说明:
In this question, to find out the number of ways to we can climb the stairs, we can use a recursive method to solve it. We can call the recursive function thrice in our code with parameters of (N-1), (N-2) and (N-3) steps (the decrease in steps show the number of steps climbed). And add and return them.
在这个问题中,要找出爬楼梯的方法 ,我们可以使用递归方法来解决。 我们可以在代码中使用(N-1) , (N-2)和(N-3)步长的参数来调用递归函数三次(步长的减少表示爬升的步数)。 并添加并返回它们。
It is one of the typical questions for recursive algorithms.
这是递归算法的典型问题之一。
Algorithm:
算法:
Step 1: Declare a recursive function staircase with one parameter (int steps).
步骤1:声明具有一个参数的递归函数阶梯 ( int步 )。
Step 2: Base Case:
步骤2:基本案例:
if(steps <0) // No steps to climb
if(steps <0) //没有要爬的步骤
return 0;
返回0;
Step 3: Base Case 2:
步骤3:基本案例2:
if(steps ==0) //Already reached top
if(steps == 0) //已经到达顶部
return 1;
返回1;
Step 4: Return staircase (steps -1) + staircase (steps – 2) + staircase (steps -3).
步骤4:返回楼梯(步骤-1)+楼梯(步骤– 2)+楼梯(步骤-3) 。
i.e. the total ways in which we can climb the steps.
也就是说,我们可以爬上台阶的全部方法。
Example:
例:
For stairs = 3.
Ways to climb are,
1 1 1
1 2
2 1
3
Hence there are four ways to climb.
C++ program:
C ++程序:
#include<bits/stdc++.h>
using namespace std;
//Recursive Function
int staircase(int n){
if(n<0){ //Base Case 1
return 0;
}
if(n==0){ //Base Case 2
return 1;
}
int count = 0;
count += staircase(n-1); //Stepping 1 step
count += staircase(n-2); //Stepping 2 step
count += staircase(n-3); //Stepping 3 step
return count;
}
//Main
int main(){
int n;
cout<<"Enter number of stairs"<<endl;
cin>>n;
cout<<"No of ways to climb stairs are ";
cout<<staircase(n)<<endl;
return 0;
}
Output
输出量
Enter number of stairs
5
No of ways to climb stairs are 13
翻译自: https://www.includehelp.com/cpp-programs/stair-case-program-to-solve-the-staircase-problem.aspx
程序设计爬楼梯问题