solution.md 2.2 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3
# 爬楼梯
<p>假设你正在爬楼梯。需要 <em>n</em>&nbsp;阶你才能到达楼顶。</p><p>每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?</p><p><strong>注意:</strong>给定 <em>n</em> 是一个正整数。</p><p><strong>示例 1:</strong></p><pre><strong>输入:</strong> 2<strong><br />输出:</strong> 2<strong><br />解释:</strong> 有两种方法可以爬到楼顶。1.  1 阶 + 1 阶2.  2 阶</pre><p><strong>示例 2:</strong></p><pre><strong>输入:</strong> 3<strong><br />输出:</strong> 3<strong><br />解释:</strong> 有三种方法可以爬到楼顶。1.  1 阶 + 1 阶 + 1 阶2.  1 阶 + 2 阶3.  2 阶 + 1 阶</pre>
<p>以下错误的选项是?</p>
F
fix bug  
feilong 已提交
4

每日一练社区's avatar
每日一练社区 已提交
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
## aop
### before
```cpp
#include <bits/stdc++.h>
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<int> 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<int> 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;
    }
};
```