最长公共子序列lcs


分析:动态规划

dp[i][j] 表示字符串A以第i个位置 ,字符串B以第j个位置的最长公共子序列的长度

dp[i][j] = dp[i - 1][j - 1] + 1 if a[i] == a[j]

else dp[i][j] == max(dp[i - 1][j] , dp[i][j - 1]);

最大长度就是 dp[n][m] ,n A的长度 ,mB的长度

还原字符串 ,只需要回到 dp[i][j] 刚开始发生改变的地方即可





#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 1E3 + 10;
char a[maxn],b[maxn],ans[maxn];
int dp[maxn][maxn];
int main(){
        scanf("%s%s",a + 1,b + 1);
        int n = strlen(a+1),m = strlen(b+1);
        memset(dp,0,sizeof(dp));
        for(int i = 1 ; i <= n ; ++i){
                for(int j = 1 ; j <= m ; ++j){
                        if(a[i] == b[j]){
                                dp[i][j] = dp[i-1][j-1] + 1;
                        }else dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
                }
        }
        int cur = 0;
        for(int i = n,j = m;dp[i][j];--i,--j){//返回到第一次更新值的地方
                while(dp[i][j] == dp[i - 1][j])     --i;
                while(dp[i][j] == dp[i][j - 1])     --j;
                ans[cur++] = a[i];
        }
        reverse(ans,ans+cur);
        ans[cur] = '';
        printf("%s
",ans);
        return 0;
}


原文地址:https://www.cnblogs.com/bryce1010/p/9387165.html