Dynamic programming is a fantastic strategy for finding an efficient and optimal solution to a variety of situations.
To put it another way, the idea of dynamic programming is to break problems down into sub-problems and save the results so that we don't have to solve the same problem twice. The optimal substructure property refers to the further optimization of sub-problems that improves the overall solution.
There are two ways to use dynamic programming:
The problem is broken down in this procedure, and if the problem has already been solved, the saved value is returned; otherwise, the function's value is memoized, which means it will be calculated for the first time; else, the stored value will be called back. For computationally expensive programs, memorization is a wonderful way to go. Don't mix up memorization and memorization.
This is a good technique to avoid recursion since it reduces the time complexity that recursion creates (i.e. memory cost because of recalculation of the same values). The solutions to little problems are calculated here, which add up to the overarching problem's solution.
Read More About Dynamic Programming.
Knowing When and How to Use This Technique:
As previously said, if you see that the problem can be broken down into sub-problems, and that these can be broken down into even smaller ones, and that some of these overlaps, this indicates that the problem can be broken down into sub-problems (i.e. requires the computation of previously calculated values). The main purpose is to reduce the repetition of values in the code by saving the results of sub-problems.
Dynamic Programming and Recursion:
Remember that dynamic programming is not the same as recursion.
Recursion is a method of locating a solution by directly or indirectly expressing the value of a function in terms of other values of that function, and such a function is known as a recursive function. It employs a top-down strategy.
Dynamic programming is nothing more than recursion with memorization, i.e. calculating and storing values that can be later accessed to solve recurring subproblems, resulting in speedier code and lower time complexity (computing CPU cycles are reduced).
Dynamic programming is a powerful tool for reducing code complexity. This technique is really simple to learn and master, although it does take some practice.