力扣(LeetCode)试题70-爬楼梯 C++代码
方法:找着找着规律,发现是斐波那契数列,还是使用迭代的方法,驾轻就熟了,第一次一遍过
1 //找规律过程中,发现是斐波那契数列 f(n) = f(n-1) + f(n-2)
2
3 #include <iostream>
4
5 using namespace std;
6
7 class Solution
8 {
9 public:
10 int climbStairs(int n)
11 {
12 if (n == 1) return 1;
13 else if (n == 2) return 2;
14 else
15 {
16 int pre_1 = 1;
17 int pre_2 = 2;
18 int cur;
19 for (int k = 3; k <= n; k++)
20 {
21 cur = pre_1 + pre_2;
22 pre_1 = pre_2;
23 pre_2 = cur;
24 }
25 return cur;
26 }
27 }
28 };
29
30 int main()
31 {
32 int n = 7;
33 int result;
34 Solution sol;
35 result = sol.climbStairs(n);
36 cout << result << endl;
37
38 int u;
39 cin >> u;
40 return 0;
41 }