Key points of dynamic programming
DP trilogy :
a. Define the sub-problems, b. Define the state array, c. Define the state transition equation.
Two core points of dynamic programming : state transition equation and boundary conditions.
Taking the house-breaking problem as an example, the
longest common sub-sequence problem is solved by transforming it into a two-dimensional array. Generally, it is necessary to set the 0th row and the 0th column to all zeros. When calculating dp[i][j], dp[i-1][j-1] will not cross the boundary
1143. The longest common subsequence problem is explained using the following figure:
Code:
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m = len(text1)
n = len(text2)
dp= [[0]*(n+1) for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if text1[i-1] == text2[j-1]:
dp[i][j] =1 +dp[i-1][j-1]
else:
dp[i][j] = max(dp[i-1][j],dp[i][j-1])
return dp[-1][-1]
The longest subsequence problem is generally solved using dynamic programming.
Supplements to permutation and combination problems:
518. The
number of change exchange II permutations is ordered. For example, s1=[1,2,2] and s2=[2,1,2] are two different results. The combination number is disordered, and s1 and s2 are It is regarded as the same result;
for a double loop, what is the outer layer will limit what, if the outer layer is the number of coins, then the order in which the coins appear is restricted, that is, the number of combinations of amounts when coin k must be used, for change Exchange, this is a matter of combination. We don't care about the order of the change, only whether the change is used or not;
The following is a better solution:
climb stairs and exchange coins to understand the number of combinations and permutations
to sum up
The general form of the dynamic programming problem is to find the extreme value. The core of solving the dynamic programming problem is exhaustion, but this exhaustion is special because there are repeated sub-problems in this type of problem. If brute force exhaustion is used, the efficiency is low, so dp is needed. table to optimize the enumeration process and avoid unnecessary calculations.
There are many dynamic programming questions, so you should brush more questions and practice more to have a better grasp.