zoukankan      html  css  js  c++  java
  • leetcode70. 爬楼梯 🌟

    题目:

      假设你正在爬楼梯。需要 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)
    解答:

    class Solution:
        def climbStairs(self, n: int) -> int:
            g = 0
            f = 1
            while n > -1:
                g = g + f
                f = g - f
                n -= 1
            return g
    View Code
    class Solution:
        def climbStairs(self, n: int) -> int:
            a = 1
            b = 1
            for _ in range(n - 1):
                a, b = b, a + b
            return b
    # https://leetcode-cn.com/problems/climbing-stairs/solution/70-climbing-stairs-dong-tai-gui-hua-fei-bo-na-qi-s
    View Code
    class Solution:
        def climbStairs(self, n: int) -> int:
            if n < 2:
                return n
    
            dp = [0] * n
            dp[0] = 1
            dp[1] = 2
    
            for i in range(2, n):
                dp[i] = dp[i - 1] + dp[i - 2]
    
            return dp[-1]
    View Code
    class Solution:
        # 作者:QQqun902025048
        # 链接:https://leetcode-cn.com/problems/two-sum/solution/2-xing-python-dong-tai-gui-hua-by-knifezhu/
        
        # dp递归方程:到达当前楼梯的路径数 = 到达上个楼梯的路径数 + 到达上上个楼梯的路径数
        # 这里用一个元组 r 来储存(当前楼梯路径数,下一层楼梯路径数)
        # 利用 reduce 来代替for循环
        def climbStairs(self, n: int) -> int:
            from functools import reduce
            return reduce(lambda r, _: (r[1], sum(r)), range(n), (1, 1))[0]
    View Code
    class Solution:
         def climbStairs(self, n: int) -> int:
             return self.climbStairsImpl(n)
     
         def climbStairsImpl(self, n: int, memo={}) -> int:
             if n < 3:
                 return n
             if n in memo:
                 return memo[n]
             else:
                 tmp = self.climbStairsImpl(n - 1, memo) + self.climbStairsImpl(n - 2, memo)
                 memo[n] = tmp
                 return tmp
    View Code
  • 相关阅读:
    sentinel-initFunc&控制台
    Sentinel-FlowSlot
    Sentinel-AuthoritySlot&SystemSlot&LogSlot
    Sentinel-DegradeSlot
    Sentinel-ClusterBuilderSlot
    Sentinel-NodeSelectorSlot
    Sentinel整体架构
    Recyclers对象池设计
    加密算法的使用场景
    FastDFS分布式
  • 原文地址:https://www.cnblogs.com/catyuang/p/11178886.html
Copyright © 2011-2022 走看看