最长公共子序列

输入样例:

4 5
acbd
abedc

输出样例:

3


集合f[i][j]: 所有在第一个序列的前i个字母中出现,且在第二个序列的前j个字母中出现的子序列

属性:最大值max。

包含与不包含a[i] b[j]的情况,都不包含a[i] b[j]的情况:00: f[i-1][j-1], 都包含a[i] b[j]的情况:11: f[i-1][j-1] + 1。

但是f[i-1][j], f[i][j-1]并不是严格的是包含a[i] 或 b[j]的最长公共子序列的最大长度,可能两者相等的位置在之前。但是包含01 或 10的。然后这两者都是包含在f[i][j]中的。

f[i-1][j-1]也是被包含囊括在内的,一般也不用写。

f[i-1][j], f[i][j-1], f[i-1][j-1] + 1三种。

#include <iostream>
#include <algorithm>
using namespace std;

const int N = 1010;

char a[N],b[N];
int f[N][N];

int main()
{
    int n,m;
    cin>>n>>m>>a+1>>b+1;
    
    for(int i = 1;i <=n;i++)
        for(int j = 1; j <= m; j++)
        {
            f[i][j] = max(f[i-1][j], f[i][j-1]);
            if(a[i] == b[j]) f[i][j] = max(f[i][j], f[i-1][j-1] + 1);
        }
    cout<<f[n][m]<<endl;
}

输入

4 5
acbd
abedc

输出

1 1 1
1 2 1
1 3 1
1 4 1
1 5 1

2 1 1
2 2 1
2 3 1
2 4 1
2 5 2

3 1 1
3 2 2
3 3 2
3 4 2
3 5 2

4 1 1
4 2 2
4 3 2
4 4 3
4 5 3

max: 3
原文地址:https://www.cnblogs.com/longxue1991/p/12748835.html