Optimize Dynamic Programming
Optimize space and remove corner cases
Example: Leetcode 518. Coin Change 2 1) Original Code:
2) Remove Corner case: Expand dp array size to cover corner cases In this case, we increase j. We should do the following:
Increase dp[] size from j to j+1
Shift variable j in for loop by 1
Shift all the table[j] to table[j-1] in the j for loop
Remove duplicated corner case checking
Return dp[j+1]
3) Decrease Dimension: Change the loop sequence Can we decrease the rp from two dimension to one dimension? We can see that dp[][j] only depends on dp[][j-1], while dp[i][] depends on dp[0:i-1][]
Switch the j and i loop
Remove the dimension that is associated with j
Check if we can remove corner cases' condition
Question:
Leetcode 188. Best Time to Buy and Sell Stock IV
Reverse thinking: think from end to beginning
Situation
When the following dp table can affect the previous filling dp table.
Question:
Leetcode 312. Burst Balloons
Last updated