程序设计爬楼梯问题_楼梯案例:解决楼梯问题的C ++程序
程序設計爬樓梯問題
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 11 22 13Hence there are four ways to climb. .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}} .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}}C++ program:
C ++程序:
#include<bits/stdc++.h>using namespace std;//Recursive Function int staircase(int n){if(n<0){ //Base Case 1return 0;}if(n==0){ //Base Case 2return 1;}int count = 0;count += staircase(n-1); //Stepping 1 stepcount += staircase(n-2); //Stepping 2 stepcount += staircase(n-3); //Stepping 3 stepreturn 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
程序設計爬樓梯問題
總結
以上是生活随笔為你收集整理的程序设计爬楼梯问题_楼梯案例:解决楼梯问题的C ++程序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 轮询锁使用时遇到的问题与解决方案!
- 下一篇: 手机子王掩码和网关查找_C程序使用位掩码