首页 > 其他 > 详细

爬楼梯

时间:2018-04-05 17:02:28      阅读:189      评论:0      收藏:0      [点我收藏+]

中英题面

  你正在爬楼梯。距离顶部还有 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

爬楼梯

原文:https://www.cnblogs.com/Efve/p/8723288.html

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