Dynamic Programming
Theory
Dynamic programming is both a mathematical optimization method and a computer programming method. The method was developed by Richard Bellman🧐 in the 1950s and has found applications in numerous fields, from aerospace engineering to economics.
In both contexts it refers to simplifying a complicated problem by breaking it down into simpler sub-problems. If a problem can be solved optimally by breaking it into sub-problems and finding the optimal solutions to the sub-problems, then it is said to have optimal substructure.
The means that dynamic programming problems have an ordering of simpler to more complex problems and those have problems have a optimal substructure.
These problems often involve recursion. If sub-problems can be nested recursively inside larger problems, so that dynamic programming methods are applicable, then there is a relation between the value of the larger problem and the values of the sub-problems.
Tips to remember
- Recursion is a way to solve problems from bigger to smaller, and it will not record any subsolutions. Only considers:
- Base Case (the smallest problem we have to solve)
- Recursive Rule
- Dynamic Programming solves problems from smaller to bigger, and it will record subsolutions. It considers:
- Mathematical Expression (??)
- Base Case
- Induction rule (??)
- Subsolution which its size < n $\rightarrow$ Solution which its size = n
Why Dynamic programming can solve problems like how to get an optimal solution (try to figure out the MIN or MAX result), because it will consider every situation.
Programming Problems
0-1 Knapsack Problem
W
to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1]
and wt[0..n-1]
which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[]
such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item or don’t pick it (0-1 property).
|
|
Change Making Problem
You are given an integer array
coins representing coins of different denominations and an integer
amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
Example:
|
|
|
|