The longest common subsequence (LCS) is the classic DP problem, which is the LCS of the sequence A[1...N], b[1..m].
The status is Dp[i][j], which represents the LCS of A[1..I],B[1..J].
The DP transfer equation is
dp[i][j]=
Dp[i-1][j-1]+1, a[i] = = B[j]
max{dp[i][j-1], Dp[i-1][j]}, a[i]! = B[i]
-------------------------------------------------------------------------------------------
Time complexity O (n^2), spatial complexity 0 (n^2).
Using a scrolling array, you can reduce the complexity of the space to 0 (N).
Observing the DP transfer equation can be seen, that is, using a scrolling array, also requires two dp[2][n], a dp[n] does not work.
Because if the state is saved using only one-dimensional array dp[n], the first clause requires a right-to-left update, and the second requires a left-to-right update.
------------------------------------------------------------------------------------
The above discussion about reducing space complexity by rolling array is wrong
------------------------------------------------------------------
actually using only one-dimensional array dp[n] is also possible, just a few changes to the first transfer equation. Strictly speaking, the above discussion is not wrong, if strictly according to
dp[i][j]=
Dp[i-1][j-1]+1, a[i] = = B[j]
max{dp[i][j-1], Dp[i-1][j]}, a[i]! = B[i]
To transfer, a dp[n] is really not enough, but we delve into the next argument-"the first one requires a right -to-left update,"
If the first type is also updated from left to right, it is overwritten by dp[i][j-1] when Dp[i-1][j-1] is required .
--------------------------------------------------------------------------------------------------------------- ------------------------
Let's change the first transfer equation to
DP[I][J] = max{Dp[i-1][k]: K < J} +1
This allows you to maintain a max{Dp[i-1][k]: K < J}as long as you update from left to right.
--------------------------------------------------------------------------------------------------------------- -------------
Longest Common subsequence (LCS)