leetcode 70. Climbing Stairs ( Python )

849 阅读21分钟

描述

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.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

解析

根据题意,想走完 n 阶台阶有两种方法,第一种是先走到 n-2 台阶处然后一次跨两个台阶,第二种是先走到 n-1 台阶处然后一次跨一个台阶。这是符合斐波那契的规则的动态规划问题,时间复杂度 O(N),空间复杂度 O(1),因为程序中只用了常数个变量。

解答

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 1:
            return 1
        first = 1
        second = 2
        for i in range(3, n+1):
            tmp = first + second
            first = second
            second = tmp
        return second
    

运行结果

Runtime: 16 ms, faster than 77.41% of Python online submissions for Climbing Stairs.
Memory Usage: 11.7 MB, less than 81.23% of Python online submissions for Climbing Stairs.

每日格言:成功的诀窍在于永不改动既定的方针。

请作者坐地铁 支付宝

支付宝

微信

微信