码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 70

时间:2016-09-09 23:43:00      阅读:163      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!