freephys of Algorithm
2/8/2020 - 3:57 AM

https://leetcode.com/problems/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?

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
'''
Runtime: 28 ms, faster than 58.40% of Python3 online submissions for Climbing Stairs.
Memory Usage: 13.1 MB, less than 79.10% of Python3 online submissions for Climbing Stairs.
'''
from functools import lru_cache
class Solution:
    @lru_cache(1000)
    def fib(self, n):
        return 1 if n <= 2 else self.fib(n - 2) + self.fib(n - 1)
    
    def climbStairs(self, n: int) -> int:
        return self.fib(n+1)
'''
Runtime: 24 ms, faster than 84.20% of Python3 online submissions for Climbing Stairs.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Climbing Stairs.
'''
class Solution:
    def climbStairs(self, n: int) -> int:
        dp = [0 for _ in range(n+1)]
        dp[0] = 1
        
        for i in range(n+1):
            if i+1 < n+1:
                dp[i+1] += dp[i]
            if i+2 < n+1:
                dp[i+2] += dp[i]
        return dp[-1]
'''
Runtime: 12 ms, faster than 89.16% of Python online submissions for Climbing Stairs.
Memory Usage: 11.9 MB, less than 9.38% of Python online submissions for Climbing Stairs.
'''
class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 1: return 1
        a,b = 1,2
        for _ in range(2,n):
            a,b = b,a+b
        return b