Find the ways of climb up the stairs

Problem


A child is running up a staircase with n steps, and can hop either 1 step, 2 steps,

or 3 steps at a time. Implement a method to count how many possible ways the

a child can run up the stairs.



Answer

This question is from the "Cracking Code Interview book" and it is the same as the "Finding the number of ways to climb stairs".

Recursion through Depth first search


The simplest way is to recursively perform the DFS with backtracking. Given 3 options to choose from, the running time is $$O(3^N)$$, where N is the number of stairs.

As I mentioned earlier, it is not an optimal algorithm.

Here is the complete code

More efficient algorithm with Dynamic programming


In the previous algorithm, there are many redundant combinations repeated through the DFS search. As seen in  "Finding the number of ways to climb stairs", the ways to climb to Nth stairs can be expressed as below: $$C_n = C_{n-1} + C_{n-2} + C_{n-3}$$, where $C_n$ is the ways to run up to Nth stair. In writing, the ways to run up to  Nth stair is the sum of the ways to run up to N-1th stairs, N-2 th stair, and N-3 stair.

Based on this optimal solution structure we can build the solution bottom up. 

First, we need to set the base cases straight. For the first three stairs.

$$C_{0} = 1$$
$$C_{1} = C_{1-1} + C_{1-2} + C_{1-3} = C_{0} = 1$$
$$C_{2} = C_{2-1} + C_{2-2} + C_{2-3} = C_{1} + C_{0} = 2$$
$$C_{3} = C_{3-1} + C_{3-2} + C_{3-3} = C_{2} + C_{1} + C_{0} = 4$$

From these base cases, we can start building up the solutions from the 4th stairs following this equation.

$$C_n = C_{n-1} + C_{n-2} + C_{n-3}$$

Please, refer to "Finding the number of ways to climb stairs" for a more detailed explanation. The only difference with this question is that "Finding the number of ways to climb stairs" had only one or two stairs choices.

The running time of this algorithm is $O(N)$.

Here is the complete code in C++.


Practice statistics

10.58: to write up the inefficient solution
26:00: to write up the second solution

UPDATE(2022-06-14): Solve the problem again after refreshing my memory on the dynamic programming. Took 3 mins to write the code with the critical mistake of setting the wrong value for $C_{0}$, 0 instead of 1.

Comments

Popular posts from this blog

Planting flowers with no adjacent flower plots

Find the maximum number of bomb that can be detonated