Problem Statement
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?
Examples
Example 1
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2
Input: n = 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
Constraints
1 <= n <= 45
Intuition
This is a classic problem that can be solved using recursion. In the recursion blog, we learned how to tackle problems using recursion. Let's see how we can solve this problem with the following steps:
Identify actual problem: find ways to reach
nth
step, by climbing either 1 step or 2 steps.Identify sub problem: find way to reach
(n-1)th
or(n-2)th
step. Then we can take either 1 or 2 steps respectively to reach top.Trust that the base function works: we trust that the function, which calculates ways to reach n steps, works for all sub-problems and will provide the correct answer.
Link actual and sub-problem: Now since we have found climbStair(n-1) and climbStair(n-2) we can simply do:
$$climbStair(n)=climbStair(n-1)+climbStair(n-2)$$
Identify base case: Since we can't find ways to climb -1 stairs, we can say that:
if n<=1: return n
This will make sure our recursion does not go beyond
climbStair(0)
.
Solution
Code in Python
class Solution:
def climbStairs(self, n: int) -> int:
# base case
if n<=1:
return 1
# recursive case
return self.climbStairs(n-1)+self.climbStairs(n-2)
Code in go
func climbStairs(n int) int {
// base case
if n<=1{
return n
}
// recursive case
return climbStairs(n-1)+climbStairs(n-2)
}
Time and space complexity
Time Complexity:
$$O(2^n)$$
This occurs because with each recursive function call, two additional recursive calls are made.
Space complexity:
If you observe the code, no data structure is being used. However, due to recursion, the compiler allocates space in the heap for each recursive call on the call stack. Therefore, the space complexity is:
$$O(n)$$
Recursive call stack
Here's the recursive call stack for climbStair(5)
Conclusion
If you've noticed, this problem shares the same recurrence relation as fibonacci. So, the code is pretty much like fibonacci too. But hey, if you try running this code on LeetCode, it might throw a TimeLimitExceeded error because it's a basic recursive solution without any fancy optimizations. Don't worry, we'll jazz up this solution in the Dynamic Programming series.
Thanks for reading till the end! I hope you found something valuable in this blog. Have a wonderful day.
Comment below on what you'd like to see improved in these blogs.