C++爬楼梯
假设有n阶楼梯。一个人要从第1阶走到第n阶。一次最多能跨越的台阶数也是给定的。根据这些信息,我们需要找到到达第n阶楼梯的所有可能方法。假设一个人每次最多能跨越两阶楼梯。那么我们可以找到递归关系来解决这个问题。一个人可以从(n-1)阶或(n-2)阶走到第n阶。所以ways(n) = ways(n-1) + ways(n-2)。
例如,楼梯数为10,一次最多能跨越的台阶数为2,则输出将是89种可能的方法。
要解决这个问题,请遵循以下步骤:
- 定义一个与楼梯数大小相同的数组count
- count[0] := 1
- 对于 i := 2 到 stair -1,执行:
- count[i] := 0
- 对于 j = 1 到 i 且 j <= max,执行:
- count[i] := count[i] + count[i - j]
- 返回 count[stair - 1]
让我们来看一下实现,以便更好地理解
示例 (C++)
#include<iostream>
using namespace std;
int stairClimbWays(int stair, int max){
int count[stair]; //fill the result stair using bottom up manner
count[0] = 1; //when there are 0 or 1 stair, 1 way to climb
count[1] = 1;
for (int i=2; i<stair; i++){ //for stair 2 to higher
count[i] = 0;
for(int j=1; j<=max && j<=i; j++)
count[i] += count[i-j];
}
return count[stair-1];
}
int countWays(int stair, int max){ //person can climb 1,2,...max stairs at a time
return stairClimbWays(stair+1, max);
}
int main (){
int stair, max;
cout << "Enter number of stairs: "; cin >> stair;
cout << "Enter max stair a person can climb: "; cin >> max;
cout << "Number of ways to reach: " << countWays(stair, max);
}输入
Stairs = 10 Max stairs a person can climb: 2
输出
Enter number of stairs: 10 Enter max stair a person can climb: 2 Number of ways to reach: 89
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP