计算到达第 n 级台阶的方法
有 n 个台阶。一个人将从第 1 个台阶走到第 n 个台阶。还会给出他/她一次最多可以跨过台阶数的最大值。有了这些信息,我们必须找到到达第 n 个台阶的可能方法。
让我们考虑一下,可以每一步最多跨过两个台阶。因此,我们可以找到递归关系来解决此问题。可以从第 (n-1) 个台阶或从第 (n-2) 个台阶移动到第 n 个台阶。因此,ways(n) = ways(n-1) + ways(n-2)。
输入和输出
Input: The number of stairs, say 10 the maximum number of stairs that can be jumped in one step, say 2 Output: Enter number of stairs: 10 Enter max stair a person can climb: 2 Number of ways to reach: 89
算法
stairClimpWays(stair, max)
输入 − 台阶数、一次最大跨越台阶数。
输出 − 可以到达的可能方法数。
Begin define array count of size same as stair number count[0] := 1 count[0] := 1 for i := 2 to stair -1, do count[i] := 0 for j = 1 to i and j <= max; do count[i] := count[i] + count[i - j] done done return count[stair - 1] End
示例
#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);
}输出
Enter number of stairs: 10 Enter max stair a person can climb: 2 Number of ways to reach: 89
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP