Leetcode-Easy 70. Climbing Stairs

简介: Leetcode-Easy 70. Climbing Stairs

21. Merge Two Sorted Lists


  • 描述:
    有n阶楼梯,每步只能走1个或2个台阶,请问到达第n阶楼梯一共有多少走法?

    1.png
  • 思路:
    动态规划
    程序从 i=3 开始迭代,一直到 i=n 结束。每一次迭代,都会计算出多一级台阶的走法数量。迭代过程中只需保留两个临时变量a和b,分别代表了上一次和上上次迭代的结果。 为了便于理解,我引入了temp变量。temp代表了当前迭代的结果值。
  • 代码

class Solution:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        # 递归 time limit
#         if n==1 or n==2:
#             return n
#         return Solution.climbStairs(self,n-1)+Solution.climbStairs(self,n-2)
        ## 备忘录算法 time limit
#         data={}
#         if n==1 or n==2:
#             return n
#         if n in data:
#             return data['n']
#         else:
#             value=Solution.climbStairs(self,n-1)+Solution.climbStairs(self,n-2)
#             data['n']=value
#             return value
        ## 动态规划
        if n==1 or n==2:
            return n
        first=1
        second=2
        temp=0
        for i in range(n-2):
            temp=first+second
            first=second
            second=temp
        return temp


相关文章
LeetCode 70. Climbing Stairs
你正在爬楼梯。 它需要n步才能达到顶峰。 每次你可以爬1或2步。 您可以通过多少不同的方式登顶? 注意:给定n将是一个正整数。
52 0
LeetCode 70. Climbing Stairs
LeetCode 70. 爬楼梯 Climbing Stairs
LeetCode 70. 爬楼梯 Climbing Stairs
|
算法 移动开发
[LeetCode]--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? 这是一个很经典的爬楼梯问题,面试也会经常遇
1148 0
LeetCode 70 Climbing Stairs(爬楼梯)(动态规划)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50514606 翻译 你正在爬一个楼梯。
927 0
|
C++ Python
[LeetCode] Climbing Stairs
Note: If you feel unwilling to read the long codes, just take the idea with you. The codes are unnecessarily long due to the inconvenient handle of matrices.
703 0
|
算法 Python
leetcode 70 Climbing Stairs
 Climbing Stairs                       You are climbing a stair case. It takes n steps to reach to the top.
1118 0
|
机器学习/深度学习
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
40 6
|
1月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
68 2