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?
OR
There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Example 4:
|
|
Solution
Method 1 - Recursion
We can easily find recursive nature in above problem.
Lets take n = 2, then we have 2 ways - either take 1 step twice or 2 steps in one go.
For n = 3, we have 3 ways:
- One Step at a time
- Two-step then one step
- One step then Two-step
For n = 4, we have 5 ways: (1, 1, 1, 1), (2, 2), (1, 1, 2), (2, 1, 1), (1, 2, 1)
Now, lets take n = 6, and try to get the algorithm.
So in the next step, we need to calculate the number of ways taken to raise 5 steps and 4 steps.
We can build full tree for the steps taken as below (not complete for clarity):
Complexity
- ⏰ Time complexity:
O(2^n)
- 🧺 Space complexity:
O(n)
Code
|
|
Method 2 - Top Down DP
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)
Method 3 - Bottom UP DP
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)
Method 4- Using Fibonacci Numbers
The number of ways to reach the n-th stair on a staircase depends on whether you can take one step at a time (from the (n-1)th stair) or two steps at a time (from the (n-2)th stair). We’ll represent this total number of ways to reach the n-th stair as ways(n)
.
|
|
This is actually formula for generating nth fibonacci number.
But notice one thing that ways(n)
is equal to fib(n+1)
, hence we can reuse fib(n)
function.
|
|
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
. (It can be optimized to work in O(Logn) time using matrix approach) - 🧺 Space complexity:
O(n)