使用步長為1、2或3的C++方法計算到達第n階樓梯的方法數
假設樓梯共有n階。一個人一次可以跨越1、2或3階。目標是找到到達樓上所有可能的走法。
我們將使用遞迴方法,記住為了到達任何第i階,一個人必須從第i-1階(跨越1階)、第i-2階(跨越2階)或第i-3階(跨越3階)跳躍過來。
讓我們用例子來理解。
輸入
N=3 steps
輸出
Count of ways to reach the nth stair using step 1, 2 or 3 are: 4
解釋
There are total 3 steps Jump from start ( skip 3 ) : 3 step Jump from 1’st step (skip 2): 1+2 Jump from 2nd step (skip 1): 2+1 No skip 1+1+1
輸入
N=6 steps
輸出
Count of ways to reach the nth stair using step 1, 2 or 3 are: 24
解釋
There are total 6 steps Ways: 1+1+1+1+1+1, 2+1+1+1+1, 3+1+1+1, 3+1+2, 3+2+1, 3+3 and so on.
下面程式中使用的方法如下:
我們將整數steps作為總步數。
函式stairs_step(int steps)接收總步數作為輸入,並返回所有可能的到達樓上的方法數。
將初始變數count設定為0,表示方法數。
如果步數為0,則返回1。
如果步數為1,則只有一種方法。
如果步數為2,則只有兩種方法(1+1或2)。
否則,方法數 = stairs_step(step-3) + stair_step(step-2) + stair_step(step-1)。
(遞迴方法)
示例
#include <iostream>
using namespace std;
int stairs_step(int steps){
if(steps == 0){
return 1;
}
else if(steps == 1){
return 1;
}
else if (steps == 2){
return 2;
}
else{
return stairs_step(steps - 3) + stairs_step(steps - 2) + stairs_step(steps - 1);
}
}
int main(){
int steps = 5;
cout<<"Count of ways to reach the nth stair using step 1, 2 or 3 are: "<<stairs_step(steps);
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出:
Count of ways to reach the nth stair using step 1, 2 or 3 are: 13
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP