Description
假如有n个台阶,一次只能上1个台阶或2个台阶,请问走到第n个台阶有几种走法?为便于读者理解题意,这里举例说明如下:假如有3个台阶,那么总计就有3种走法:第一种为每次上1个台阶,上3次;第二种为先上2个台阶,再上1个台阶;第三种为先上1个台阶,再上2个台阶。输入为n,输出为走到第n个台阶有几种走法
Input
比如输入是3
Output
如果输入是3,走到第3个台阶的走法总计有3种,1,1,1 和 1,2 和2,1,输出为3
Sample Input 1
1
Sample Output 1
1
Sample Input 2
3
Sample Output 2
3
Sample Input 3
4
Sample Output 3
5
code
方法一:递归,适用于数据范围比较小的题
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1e5 + 10;
int a[N];
int n, res;void jump(int k) {if (k == n) {res ++ ;} else if (k < n) {jump(k + 1);jump(k + 2);}
}void solve() {cin >> n;jump(0);cout << res << "\n";
}int main() {ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);int _ = 1;// cin >> _;while (_ -- ) {solve();}return 0;
}
方法二:用数组计算,适用于数据量稍大的题目
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1e5 + 10;
int a[N];
int n, res;void solve() {a[1] = 1;a[2] = 2;for (int i = 3; i <= 15; i ++ ) {a[i] = a[i - 1] + a[i - 2];}cin >> n;cout << a[n] << "\n";
}int main() {ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);int _ = 1;
// cin >> _;while (_ -- ) {solve();}return 0;
}