题意: 给两个字符串, 要你求出两个字符串的最长公共子序列长度
详解:https://blog.csdn.net/u013480600/article/details/40741333
上述公式: 当str1[i]==str2[j]时, str1的第i个字符和str2的第j个字符必然在str1[1..i]和str2[1..j]的最长公共子序列中, 所以f[i][j]==dp[i-1][j-1]+1.
当str1[i]!=str2[j]时,str1[i]和str2[j]至少有一个是不可能在str1[1..i]和str2[1..j]的最长公共子序列中的, 所以f[i][j] = max( f[i-1][j] ,f[i][j-1] )
模板代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
int f[1001][1001];//**1001*1001太大不能定义在主函数,否则直接停止编译**//
char str1[1001],str2[1001];
int main()
{
while(~scanf("%s%s",str1,str2))
{
int n1=strlen(str1);
int n2=strlen(str2);
for(int i=0;i<=n1;i++)
f[i][0]=0;
for(int i=0;i<=n2;i++)
f[0][i]=0;
for(int i=1;i<=n1;i++)
{
for(int j=1;j<=n2;j++)
{
if(str1[i-1]==str2[j-1])
f[i][j]=f[i-1][j-1]+1;
else
f[i][j]=max(f[i-1][j],f[i][j-1]);
}
}
printf("%d\n",f[n1][n2]);
}
return 0;
}