DP
When to use dynamic programming?
If we can break the problem into subproblems such that
the original problem can be solved relatively easily once solutions to the subproblems are available
we solve some subproblems repeatedly
we can cache the solution to subproblems
The question usually asks for maximum or minimum.
Top-down or bottom-up
top-down:
The question we should ask is: what if the first element is used, what if it's not used?
Usually we can visualize the solution in a tree from top to bottom.
Recursion is often used.
If it's a dynamic programming problem, we can cache the solutions along the way.
Very similar to backtracking solutions. The difference is in backtracking problems, we have to traverse the whole tree to return all the output. But in dynamic programming, we don't need to return all the path. Usually we are updating something along the way.
bottom-up:
The question we should ask is: if we have the solution to the subproblem A[0:n-2], how can we find solution for adding one more element A[n-1]?
We won't traverse the tree, instead there will be linear search.
Iteration is often used.
One advantage of bottom-up is that when processing some paths will be pruned early.
In a dynamic programming problem, try to come up a bottom-up solution first because bottom-up costs less space.
Two typical ways when cache results
cache a constant number of results.
In bottom-up solution, when we add element A[n-1] , the information we need from solution to the subproblem A[0:n-2] is up to constant.
Example: 53_Maximum Subarray
cache in a array of the same length as the input
In bottom-up solution, when we add element A[n-1] , the information we need from solution to the subproblem A[0:n-2] is related with each element.
Example: 300_ Longest Increasing Subsequence
Last updated