Think:
1递推关系:
a[i][j] = 0//i == 0 || j == 0
a[i][j] = a[i-1][j-1] + 1//st1[i-1] == st2[j-1]
a[i][j] = max(a[i-1][j], a[i][j-1])//st1[i-1] != st2[j-1]
2建议参考博客
3博客参考图片,以下图片来自于建议参考博客
最长公共子序列问题
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
给定两个序列X=
Input
输入数据有多组,每组有两行 ,每行为一个长度不超过500的字符串(输入全是大写英文字母(A,Z)),表示序列X和Y。
Output
每组输出一行,表示所求得的最长公共子序列的长度,若不存在公共子序列,则输出0。
Example Input
ABCBDAB
BDCABA
Example Output
4
Hint
Author
以下为Accepted代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
int len1, len2, a[504][504], i, j;///a数组记录已经解决的子问题
char st1[504], st2[504];
while(scanf("%s", st1) != EOF)
{
scanf("%s", st2);
len1 = strlen(st1);
len2 = strlen(st2);
memset(a, 0, sizeof(a));
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
if(st1[i-1] == st2[j-1])
a[i][j] = a[i-1][j-1] + 1;///递推关系
else
a[i][j] = max(a[i-1][j], a[i][j-1]);///递推关系
}
}
printf("%d\n", a[len1][len2]);
}
return 0;
}
/***************************************************
User name:
Result: Accepted
Take time: 148ms
Take Memory: 1140KB
Submit time: 2017-04-15 18:54:39
****************************************************/