leetcode_70. 爬楼梯

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

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

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

示例 1:

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

输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1.  1 阶 + 1 阶 + 1 阶
2.  1 阶 + 2 阶
3.  2 阶 + 1 阶

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/climbing-stairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution:
    def climbStairs(self, n: int) -> int:
        if n==1:return 1
        if n==2:return 2
        return self.climbStairs(n-1)+self.climbStairs(n-2)
执行结果:超出时间限制
显示详情最后执行的输入:
38
#增加字典保存递归中间值
class Solution:
    dic={1:1,2:2}
    def climbStairs(self, n: int) -> int:
        
        if n in self.dic:
            return self.dic[n]
        else:
            t=self.climbStairs(n-1)+self.climbStairs(n-2)
            self.dic[n]=t
            return self.dic[n]
class Solution:
    def climbStairs(self, n: int) -> int:
        a=1
        b=2
        t=0
        if n==1 :return 1
        if n==2 :return 2
        for i in range(3,n+1):
            t=a+b
            a=b
            b=t
        return t
原文地址:https://www.cnblogs.com/hqzxwm/p/14042256.html