爬楼梯

中英题面

  你正在爬楼梯。距离顶部还有 n 台阶。

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

  每次你可以爬 1 或 2 个台阶。你有多少种不同的方式可以爬到楼顶呢?

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

  注意:给定 n 将是一个正整数。

  Note: Given n will be a positive integer.

 

  示例 1:

  输入: 2
  输出: 2
  说明: 有两种方法可以爬到顶端。

  1.  1 步 + 1 步
  2.  2 步

  Example 1:

  Input: 2
  Output:  2
  Explanation:  There are two ways to climb to the top.

  1. 1 step + 1 step
  2. 2 steps

 

  示例 2:

  输入: 3
  输出: 3
  说明: 有三种方法可以爬到顶端。

  1.  1 步 + 1 步 + 1 步
  2.  1 步 + 2 步
  3.  2 步 + 1 步

  Example 2:

  Input: 3
  Output:  3
  Explanation:  There are three ways to climb to the top.

  1. 1 step + 1 step + 1 step
  2. 1 step + 2 steps
  3. 2 steps + 1 step

 

 

 

题目解读
  设 f[i] 表示上 i 级台阶的方案数,显然 f[0] = f[1] = 1,而当 i > 1 时,f[i] = f[i - 1](走一个台阶) + f[i - 2](走两个台阶),因此所求答案即为斐波那契数列的 N - 1 项。

 

算法
  使用递推公式直接迭代计算斐波那契数列,算法时间复杂度 O(N)。
 
代码
 1 class Solution:
 2     def climbStairs(self, n):
 3         """
 4         :type n: int
 5         :rtype: int
 6         """
 7         x = 0
 8         y = 1
 9         for i in range(n):
10             x += y
11             x, y = y, x
12         return y
posted @ 2018-04-05 16:54  Efve  阅读(202)  评论(0编辑  收藏  举报