Solution: Staircase Problem
This review contains a detailed analysis of the different ways to solve the staircase problem.
Solution #1: Brute force
Let’s look at the brute force solution first:
Press + to interact
class StairCaseProblem{//returning count of ways to reach the nth stair//either using 1 hop, 2 hops or 3 hopspublic static int countWays(int n){if (n < 0)return 0;else if (n == 0)return 1;elsereturn countWays(n-1) + countWays(n-2)+ countWays(n-3);}//main functionpublic static void main(String args[]){System.out.println(countWays(3));}};
Explanation
The main idea is that if you have n
stairs, then you can hop either 1 step, 2 steps or 3 steps.
- If you hop 1 step, then you have remaining stairs
- If you hop 2 steps, then you have remaining stairs
- If you hop 3 steps, then you have