Dynamic Programming
dynamic programming
Dynamic Programming
A method for solving a complex problem by breaking it down into a collection of simpler subproblems, solving each of those subproblems just once, and storing their solutions.
It only works on problems with Optimal Substructure & Overlapping Subproblems
Overlapping Subproblems
A problme is said to have overlapping subproblems if it can be broken down into subproblems which are reused several times.
Ex) Finbonnaci Numbers
Optimal Substructure
A problem is said to have optimal substructure if an optimal solution can be constructed from optimal solutions of its subproblems.
Meomoization
Storing the results of expensive function calls and returning the cached result when the same inputs occur again.
The Fibonacci with Recursive
1 | function fib(num){ |
Time Complexity - O(2^n)
Meomoization : The Fibonacci with Memoized solution(Top-Down)
1 | function fib(n, memo=[]){ |
Time Complexity - O(n)
Tabulation
Storing the result of a previous result in a “table”(usually an array).
Usually done using iteration.
Better space complexity can be achieved using tabulation.
Tabulation : The Fibonacci with tabulated solution(Bottom-up Approach)
1 | function fib(n){ |
Time Complexity - O(n)
Space Complexity is better than Memoized Version.