https://blog.csdn.net/someone_and_anyone/article/details/81044153
When the position i and the string 1 and string 2 position j of the matching is successful,
dp [i] [j] = dp [i-1] [j-1] +1, that is to say in this state by the state dp [i-1] [j-1] from the transfer, with an array of records,
When the match is not successful, dp [i-1] [j] and dp [i] [j-1] to a maximum, referred to as an array 2 and 3 respectively.
Looking path based on an array of records:
When the recording of the array 1, i and j at times want to wait instructions, and this state is a i-1 and j-1 from the transfer, so that i = i-1, j = j-1
When the array is recorded. 2, this time number corresponding to i and j ranging symbol, and this state is transferred from the j-1, J, so directly;
When the array is recorded. 2, this time number corresponding to i and j ranging symbol, and this state is transferred from the i-1, so the direct i--;
#include<bits/stdc++.h> using namespace std; const int N=1000+7; int dp[N][N]; int mark[N][N]; char s1[N],s2[N]; int main() { cin>>s1+1>>s2+1; int n=strlen(s1+1); int m=strlen(s2+1); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++){ if(s1[i]==s2[j]){ dp[i][j]=dp[i-1][j-1]+1; mark[i][j]=1; } else if(dp[i][j-1]>dp[i-1][j]){ dp[i][j]=dp[i][j-1]; mark[i][j]=2; } else { dp[i][j]=dp[i-1][j]; mark[i][j]=3; } } string ans=""; int i=m,j=n; while(i>0&&j>0){ if(mark[i][j]==1) { ans+=s1[i]; i--;j--; } else if(mark[i][j]==2) { j--; } else i--; } reverse(ans.begin(),ans.end()); cout<<ans<<endl; return 0; }