leetcode--爬楼梯(低级动态规划)

leetcode–爬楼梯(低级动态规划)

题目

英文

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?
Note: Given n will be a positive integer.

中文

 假设你正在爬楼梯。需要 n 步你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。

例子:

  1. 示例 1:
    输入: 2
    输出: 2
    解释: 有两种方法可以爬到楼顶。
    1. 1 步 + 1 步
    2. 2 步
  2. 示例 2:
    输入: 3
    输出: 3
    解释: 有三种方法可以爬到楼顶。
    1– 1 步 + 1 步 + 1 步
    2– 1 步 + 2 步
    3– 2 步 + 1 步

思路

  1. 动态规划
    什么是动态规划

  2. 核心找到递推式

  3. 代码:

      def climbStairs(n):
          """
          :type n: int
          :rtype: int
          """
          if n==1:
              return 1
          if n==2:
              return 2
          i=3
          a=1
          b=2
          while i<=n:
              t=a
              a=b
              b=b+t #这里就是递归式,T[3]=T[3]+T[2]+T[1]
              #容许java程序 不用 python的 a,b=b,a+b  
              #因为每次都要创建一个元组,太消费内存
              i+=1
          return b

猜你喜欢

转载自blog.csdn.net/luohongtucsdn/article/details/81015936
今日推荐