Dear Reader, this is the second problem in dp. I hope you have understood the basics of dp, we will solve more problems to make our understanding clear.
Important Links : Problem Link, Question Video
Climb Stairs
The most damaging phrase in the language is.. it's always been done this way
~ Grace Hopper
Dear Reader, this is the second problem in dp. I hope you have understood the basics of dp, we will solve more problems to make our understanding clear.
Important Links : Problem Link, Question Video
Prerequisite:
Solve the Print Stairs Path before this, because we will only discuss the DP approach here.
We have already seen the recursion approach in Print Stairs Path.
Let's first clear one thing, if there are
x ways to go from a to D
yways to go from b to D
z ways to go from c to D
Then for going from S to D we will have x+y+zapproaches.
We are going to use the same recursive code but just memoize the result at every instant. This will prevent the same calculations from being repeated again and again. You can draw the recursion tree and check for yourself. If you find difficulty understanding this part watch the video .
So we created an array, qb of size n+1, (because we will need to store the value of n as well, and if we create an array of size n we will have an index from 0 to n-1. Also, we will pass qb to each recursion call. There it will check if the value for n is already calculated. If so, then simply return, else recalculate it and store it before returning.
java; true";
In the case of the Tabulation method, we will first create an array of size n+1 so that we can access all the indexes from 0 to n.
java; true";
O(n)
Clearly, we are performing a loop of n iterations, and each iteration we are performing O(1) operations hence overall O(n).
This problem is very similar to Fibonacci except for the fact that we are using the last 3 instead of the last 2 in the case of Fibonacci.
O(n)
We are using a single array of size n+1 hence the space complexity is linear in nature. i.e O(n)