首页 > 其他 > 详细

leetcode 70

时间:2016-09-09 23:42:49      阅读:258      评论:0      收藏:0      [点我收藏+]

70. Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

此题为典型的菲波那切数列问题;

当n=1时,有1种走法;

当n=2时,有2种走法;

当n=3时,有3种走法;

当n=4时,有5种走法;

......

当n=k时,有你n[k-1] + n[k-2]种走法;

 

代码如下:

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         if(n == 1)
 5         {
 6             return 1;
 7         }
 8         if(n == 2)
 9         {
10             return 2;
11         }
12         int a = 1;
13         int b = 2;
14         int c;
15         for(int i = 2; i < n; i++)
16         {
17             c = a + b;
18             a = b;
19             b = c;
20         }
21         return c;
22     }
23 };

 

leetcode 70

原文:http://www.cnblogs.com/shellfishsplace/p/5858175.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!