求两个字符串的最长公共子序列(Longest common subsequence)
Given two sequences.Find the length of the longest common subsequence(LCS)
Note: A subsequence is different from a substring ,for the former need NOT be consecutive of the original sequence.For example ,for “CHINA” and “CAHNI” ,the longest common subsequence is “CHN” ,and the longth of it is 2.
这道题目是比较典型的动态规划问题,笔者也是新手,为了加深印象,特意花了几张图来加深印象。先看源代码,再看图,加深印象。
/*Author:Chauncy
date:2019年12月10日*/
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str1,str2;
cin>>str1;
cin>>str2;
int m,n;
m=str1.length();
n=str2.length();
int LCS[m+1][n+1];
for(int i=0;i<m+1;i++)
LCS[i][0]=0;
for(int j=0;j<n+1;j++)
LCS[0][j]=0;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
{
if(str1[i-1]==str2[j-1])
LCS[i][j]=LCS[i-1][j-1]+1;
else
LCS[i][j]=max(LCS[i-1][j],LCS[i][j-1]);
}
cout<<LCS[m][n];
return 0;
}
首先把二维数组的第一行和第一列初始化为0

遇到相同的,按公式计算当前格子的值。











本文详细介绍了一种解决最长公共子序列(LCS)问题的动态规划算法,通过实例讲解了如何利用二维数组存储中间结果,避免重复计算,提高效率。

被折叠的 条评论
为什么被折叠?



