Finding the number of ways to climb the stairs - Part 1
Problem
You are climbing a stair case. Each time you can either make 1 step or 2 steps. The staircase has n steps. In how many distinct ways can you climb the staircase ?For example, If there are 3 stairs, there are three possible ways to climb them.
{1,1,1}, {1, 2}, {2, 1}
Your algorithm should print out the total number of ways to climb the stairs. (Optional: should also print out the different ways as above)
I will first start with the brute force approach, which does not give us ideal time complexity.
I will cover the better algorithm in Part 2. So stay tuned.
Given the two choices, 1 step or 2 steps, you can draws the Binary trees as below.
Binary Tree to find ways to climb stairs |
Running time of DFS is O(M), where M = 2^N, where N is the number of stairs.
Therefore, running time of the algorithm is O( 2^ N).
Here is the complete code running in O( 2^N).
Above algorithm give us what we want but its running time O(2^N) is not ideal.
Can we do better ? I think so, let find a better algorithm in Part 2.
Practice statistics
23 mins: to write up the code
3 mins: to fix the typos through compilation.
Comments
Post a Comment