![]() |
VOOZH | about |
A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. The task is to implement a method to count how many possible ways the child can run up the stairs.
Examples:
Input: 4
Output: 7
Explanation: There are seven ways: {1, 1, 1, 1}, {1, 2, 1}, {2, 1, 1}, {1, 1, 2}, {2, 2}, {3, 1}, {1, 3}.Input: 3
Output: 4
Explanation: There are four ways: {1, 1, 1}, {1, 2}, {2, 1}, {3}.
Table of Content
There are n stairs, and a person is allowed to jump next stair, skip one stair or skip two stairs. So there are n stairs. So if a person is standing at i-th stair, the person can move to i+1, i+2, i+3-th stair. A recursive function can be formed where at current index i the function is recursively called for i+1, i+2 and i+3 th stair.
There is another way of forming the recursive function. To reach a stair i, a person has to jump either from i-1, i-2 or i-3 th stair.
countWays(n) = countWays(n-1) + countWays(n-2) + countWays(n-3)
Below is the implementation of the above approach:
7
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure:
Number of ways to reach the nth stair, i.e., countWays(n), depends on the optimal solutions of the subproblems countWays(n-1) , countWays(n-2) and countWays(n-3). By combining these optimal substructures, we can efficiently calculate the total number of ways to reach the nth stair.
2. Overlapping Subproblems:
While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times. For example, when calculating countWays(4), we recursively calculate countWays(3) and countWays(2) and countWays(1) which in turn will recursively compute countWays(2) again. This redundancy leads to overlapping subproblems.
7
The idea is to create a 1-D array, fill values for first three stairs and compute the values from 3 to n using the previous three results. For i=3 to n, do dp[i] = dp[i-1] + dp[i-2] + dp[i-3].
Below is the implementation of the above approach:
7
The idea is to store only the previous three computed values. We can observe that for a given stair, only the result of last three stairs are needed. So only store these three values and update them after each step.
Below is the implementation of the above approach:
7
The recurrence relation for a given step is given as countWays(n) = countWays(n-1) + countWays(n-2) + countWays(n-3) starting with countWays(0)=1, countWays(1)=1, countWays(2)=2.
Refer to Matrix Exponentiation to understand how matrix exponentiation works.
Below is the implementation of the above approach:
7