DP: DFS with Memoization

class Solution:
    def climbStairs(self, n: int) -> int:
        dp = {}
 
        def dfs(i = 0):
            if i == n:
                return 1
            elif i > n:
                return 0
 
            if i in dp:
                return dp[i]
 
            dp[i + 1] = dfs(i + 1)
            dp[i + 2] = dfs(i + 2)
 
            return dp[i + 1] + dp[i + 2]
        
        return dfs()

Complexity

Time: — with memoization, we don’t need go through all nodes of the tree, just the height
Space:

Pure DP: Bottom-up approach (Optimal)

class Solution:
    def climbStairs(self, n: int) -> int:
        # By analyzing bottom-up DP approach, we can conclude that the answer
        # would be the nth Fibonacci number (excluding 0).
 
        l, r = 1, 0
        total = 0
 
        while n > 0:
            total = l + r
            l, r = total, l
            n -= 1
        
        return total

Complexity

Time:
Space:

Notes

Start from the base case (i.e ) and go backwards. Suppose , we’ll construct an array and start from this last case. We’ll ask: how many ways can we get to ? The answer since we’re already at would be and we’ll go to the previous step and ask the same question again. We can jump either or steps but we can only get to by jumping a single step. So, the no. of ways at is also . From step , we can either jump or steps and if we do so, we get to steps and respectively. But we already calculated the count at both of these steps so . If we continue, we’ll notice the following pattern:

…which resembles part of the Fibonnacci Sequence. So the answer would be the nth Fibonacci number.