As the problem states, imagine you are standing at point A and want to reach point B. There are n stoppers in between, meaning you are not at the first stop and do not want to stop at the last one.
A -> n -> B
- If n == 0, it means the starting point and the destination are the same. In this case, there is only one possible way to reach the destination.
- If n == 1, there is one stopper between A and B. There are two possible ways to reach B:
- Jump one step from A to the stopper, then another one step from the stopper to B.
- Jump two steps directly from A to B.
- Hence, for n = 1, there are two possible ways.
- If n == 2, meaning there are two stoppers between A and B, there are four possible ways to reach B:
- A → Stop1 → Stop2 → B
- A → Stop1 → B
- A → Stop2 → B
- A → B directly (3-step)
To solve this problem efficiently, we store the number of ways in a dp array
int[] dp = new int[n+1]
and use a loop
for(int i=3; i<n+1; i++){
dp[i] = dp[i-1] + dp[i-2] + dp[i-3]
}
Finally, the answer will be stored in dp[n].