Climbing Stairs
Question 1 (LC.70)
There are n stairs. Each time you can either take 1 step or 2 steps. How many distinct ways you can climb to the top?
Example
n = 1 => 1
n = 2 => 2
n = 3 => 3
n = 7 => 21
Follow Up #1
Can you do this in O(1) space?
Analysis
Notice the recurrence only uses memo[i-1], memo[i-2]. We can just use 2 constants to hold them. And update both during the tabulation.
Question 2 (LC.272)
There are n stairs. Each time you can either take 1 step or 2 steps or 3 steps. How many distinct ways you can climb to the top?
Example
Analysis
We can solve this recursively by prefix f(n) = f(n-3) + f(n-2) + f(n-1). But we spot overlapping subproblems. And we can frame this problem as an optimization problem so we also have optimal substructure. Yay! DP let's go. DP in 5 Easy Steps: 1. define subproblems - optimal substructures - prefix/suffix/substring/backpack/etc 2. recursive dp using the subproblems 3. topological order 4. initialize base cases 5. answer to the original problem
Approach
Code
Time & Space Complexity
Time - O(n) cause one for loop from i = 3 to n Space - O(n) we have n subproblems and therefore need to store n partial answers
Compress Cache
There are only 3 layers of dependency. We don't have to store the entire cache.
The space complexity is only O(1).
Question 3
There are n stairs. Each time you can either take 1, 2, 3, ..., or k steps. How many distinct ways you can climb to the top?
Analysis
Code
Time Complexity
The space is still O(n). What about time? O(n*k).
Last updated