# 爬楼梯

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

示例 1:

输入: 2
输出:
2
解释:
有两种方法可以爬到楼顶。1. 1 阶 + 1 阶2. 2 阶

示例 2:

输入: 3
输出:
3
解释:
有三种方法可以爬到楼顶。1. 1 阶 + 1 阶 + 1 阶2. 1 阶 + 2 阶3. 2 阶 + 1 阶

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; int x = 3; int res; res = sol.climbStairs(x); cout << res; return 0; } ``` ## 答案 ```cpp class Solution { public: int climbStairs(int n) { double sqrt5 = sqrt(5); double fibn = pow((1 + sqrt5) / 2, n) - pow((1 - sqrt5) / 2, n + 1); return (int)(fibn / sqrt5); } }; ``` ## 选项 ### A ```cpp class Solution { public: int climbStairs(int n) { vector s; s.push_back(1); s.push_back(2); if (n == 1) return 1; if (n == 2) return 2; for (int i = 2; i < n; i++) { s.push_back(s[i - 1] + s[i - 2]); } return s[n - 1]; } }; ``` ### B ```cpp class Solution { public: int climbStairs(int n) { vector res(n + 1, 0); res[1] = 1; res[2] = 2; for (int i = 3; i <= n; i++) res[i] = res[i - 1] + res[i - 2]; return res[n]; } }; ``` ### C ```cpp class Solution { public: int climbStairs(int n) { if (n == 1) { return 1; } int first = 1; int second = 2; for (int i = 3; i <= n; i++) { int third = first + second; first = second; second = third; } return second; } }; ```