码迷,mamicode.com
首页 > 编程语言 > 详细

力扣(LeetCode)试题70-爬楼梯 C++代码

时间:2020-07-12 22:18:34      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:==   name   div   斐波那契数列   style   stream   class   inf   http   

方法:找着找着规律,发现是斐波那契数列,还是使用迭代的方法,驾轻就熟了,第一次一遍过

 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 }

技术图片

 

力扣(LeetCode)试题70-爬楼梯 C++代码

标签:==   name   div   斐波那契数列   style   stream   class   inf   http   

原文地址:https://www.cnblogs.com/pgzhanglin/p/13289927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!