Python LeetCode(70.爬楼梯)

Python 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 阶

Solution1:(递归)

class Solution1(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 1:
            return 1
        if n == 2:
            return 2
        else:
            return self.climbStairs(n-1)+self.climbStairs(n-2)
solution1 = Solution1()
print(solution1.climbStairs(6))
13

Solution2:(递归时间太长,实际问题其实为斐波那契数列,可以使用递推产生)

class Solution2(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        prev, curr = 0, 1
        for i in range(n):
            prev, curr = curr, prev+curr
        return curr
solution2 = Solution2()
print(solution2.climbStairs(6))
13

猜你喜欢

转载自blog.csdn.net/qq_44410388/article/details/89086030