LC070 - Climbing Stairs
Problem
You are climbing a staircase. It takes n
steps to reach the top. Each time you can either climb 1
or 2
steps. In how many distinct ways can you climb to the top?
Example
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1 step + 1 step
2 steps
Solution
Naive Recursion
The naive solution is to visit every node and check for both conditions, i.e. 1 and 2 steps using recursion. The problem with this is that it takes time, because there are 2 choices at each node, and there are nodes. We use space for the recursive stack, as there are nodes.
Dynamic Programming
Notice that each smaller subtree depends on the larger tree as a whole, compute backwards. Time complexity is and space complexity is , but can be refined to be by just using two variables to hold intermediate values instead of an array.
Cache β Memoization
Subtrees are repeated, so we can store the results from each subtree so that we donβt have to compute them multiple times. Time complexity using a DP cache is .
Last updated