Ok, here is what the code does.
`if (n<0)` `return 0;`
If there are not enough steps left, then do not count. For example, if two steps remain, but the user tries to take three steps, then this is not considered a possible combination.
else if (n==0) return 1;
If the number of remaining steps corresponds to the number of available steps that the user is trying to take, this is a possible combination. So, return 1 because it is a possible combination and should be added to the total number of valid combinations.
else if (map[n]>-1) return map[n];
This is part of dynamic programming. Suppose all values ββin the array have a value of -1. So, if the number is greater than -1, it has already been decided for, so return the total number of combinations from step n instead of resolving it.
`map[n] = countDP(n-1, map) + countDP(n-2, map) + countDP(n-3, map);`
return map[n]; }
Finally, this part solves the code. The number of possible combinations is equal to the number of possible combinations that the user can receive if he takes 1 step + the number of possible combinations that the user can receive if he takes 2 steps + the number of possible combinations that the user can get if he takes three steps.
For example, suppose there are 5 steps
A simple run would look like this:
//The number of solutions from the fifth step countDp(5) = countDp(4)+countDp(3)+countDp(2); //Number of solutions from the fourth step countDP(4) = countDp(3)+countDp(2)+countDp(1); //Number of solutions from the third step countDp(3) = countDp(2)+countDp(1)+countDp(0); //Number of solutions from the second step countDp(2) = countDp(1)+countDp(0)+countDp(-1); //Number of solutions from the first step countDp(1) = countDp(0) + countDp(-1)+countDp(-2); //Finally, base case countDp(0) = 1; countDp(-1)= 0; countDp(-2)= 0; countDp(1) = 1+0+0 = 1; countDp(2) = 1+1+0 = 2; //Dynamic programming: did not have to resolve for countDp(1), instead looked up the value in map[1] countDp(3) = 2+1+1 = 4; //Dynamic programming, did not have to solve for countDp(1), countDp(2), instead looked up value in map[1] and map[2] countDp(4) = 4+2+1=7 //Dynamic programming, did not have to solve for CountDp(3),CountDp(2), CountDp(1), just looked them up in map[3],map[2],map[1] countDp(5)= 2+4+7=13 //Dynamic programming, just used map[4]+map[3]+map[2]