leetcode

Workout on LeetCode

View on GitHub

70. Climbing Stairs

If we count steps from top to bottom, things will be more easier to understand.

class Solution:
    def climbStairs(self, n: int) -> int:
        a, b = 1, 1
        for i in range(n):
            a, b = b, a + b
        return a
class Solution2:
    def climbStairs(self, n: int) -> int:
        fib = [1] * 2
        for k in range(2,n + 1):
            fib[k%2] = fib[(k-1)%2] + fib[(k-2)%2]
        return fib[n%2]

The second one is much faster than the first one which actually takes more assignment operations.


↥ back to top