题目链接
leetcode
题目描述
假设你正在爬楼梯。需要n
阶你才能到达楼顶。
每次你可以爬1
或2
个台阶。
有多少种不同的方法可以爬到楼顶?
C++ 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| #include <iostream> #include <vector> using namespace std;
class Solution { public: int climbStairs(int n) { if (n <= 2) { return n; }
int f[n+1]; f[0] = 1, f[1] = 1; for (int i = 2; i <= n; i++) { f[i] = f[i-1] + f[i-2]; }
return f[n]; } };
class Solution_1 { public: int climbStairs(int n) { if (n <= 2) { return n; } int prev = 1, cur = 1; for (int i = 2; i <= n; i++) { int next = prev + cur; prev = cur; cur = next; }
return cur; } };
int main() { Solution solution; vector<int> n_cases = { 2, 3 };
for (auto& n : n_cases) { cout << "Input: n = " << n << endl; int result = solution.climbStairs(n); cout << "Output: " << result << endl; }
return 0; }
|