思路:
//!!!!!!!!动态规划两个基本要素!!!!!!
// 1、最优子结构
// 从后往前推,x,y的最优结果包含了x,y前缀的最长公共子序列
// xn=ym,则该元素一定在最长公共子序列里面------>xn!=ym,那么就在(xn-1,ym) or(xn,ym-1)里面继续找
// 大问题变小
//2、重叠子问题
// 当Xn-1 和 Ym 的最后一个元素不相同时,将LCS(Xn-1,Ym)进行分解:
// 分解成:LCS(Xn-1,Ym-1) 和 LCS(Xn-2,Ym)
//.注意1:动态规划表!!!!避免重复计算!!!
//注意2:递归关系c:记录子序列元素个数c[n][m]=max
// c[xn,ym]=c[xn-1,ym-1] +1 ();
// c[xn, ym] =max(c[xn-1,ym]+c[xn,ym-1])(!=)
// c[xn, ym] =0(n or m0)
//
**
#include <iostream>
#include <string>
#include<stack>
using namespace std;
void LCS(string s1, string s2)
{
int m = s1.length() + 1;//使用(0->1->length)
int n = s2.length() + 1;
int **c;//记录元素个数
int **b;//记录路线方向
c = new int* [m];//二维动态数组!!!!!
b = new int* [m];
for (int i = 0; i < m; i++)//动态二维数组
{
c[i] = new int[n];//每行有n列
b[i] = new int[n];
//memset(b, 0, sizeof(b));//b数组初值0
//memset(c, 0, sizeof(c));//
for (int j = 0; j < n; j++)
b[i][j] = 0;
}
for (int i = 0; i < m; i++)
c[i][0] = 0;
for (int i = 0; i < n; i++)
c[0][i] = 0;
for (int i = 0; i < m - 1; i++)//行
{
for (int j = 0; j < n - 1; j++)//列
//c[0][j] andc[i][0]=0,不用的!!!!
{
if (s1[i] == s2[j])//共同元素
{
c[i + 1][j + 1] = c[i][j] + 1;
b[i + 1][j + 1] = 1;//左上
}
else if (c[i][j + 1] >= c[i + 1][j])
{
c[i + 1][j + 1] = c[i][j + 1];
b[i + 1][j + 1] = 2;//上
}
else
{
c[i + 1][j + 1] = c[i + 1][j];
b[i + 1][j + 1] = 3;//←
}
}
}
//输出c数据
for (int i = 0; i < m; i++)//i<=s1.length
{
for (int j = 0; j < n; j++)
{
cout << c[i][j] << ' ';
}
cout << endl;
}
//记录
stack<char> same;//最长公共字符串
stack<int> same1, same2;//对应下标
for (int i = m - 1, j = n - 1; i >= 0 && j >= 0;)//i,j=length
{
if (b[i][j] == 1)//左上
{
i--;
j--;
same.push(s1[i]);//!!!!!!!!!!c中存放是在i+1,j+1;,字符串数组中下标为i,j
same1.push(i);
same2.push(j);
}
else if (b[i][j] == 2)//上
{
i--;
/*same.push(s1[i]);
//特别容易错!!!!!!!!!!!!!!!!!!!!!!!!!
same1.push(i);
same2.push(j+1);*/
}
else
j--;
}
//输出
cout << s1<< endl; //s1
for (int i = 0; i < m && !same1.empty(); i++)
{
if (i == same1.top())//后进的先出来
{
cout << s1[i];
same1.pop();//输出过的就拿出来,top改变
}
else
cout << ' ';
}
cout << endl<<s2 << endl; //s2
for (int i = 0; i < n && !same2.empty(); i++)
{
if (i == same2.top())//后进的先出来
{
cout << s2[i];
same2.pop();//输出过的就拿出来,top改变
}
else
cout << ' ';
}
cout << endl<<"最优结果:" << endl;
while (!same.empty())
{
cout << same.top();
same.pop();//一边输出,一边拿出;
}
cout <<endl<< "长度为:" << endl;
cout << c[m - 1][n - 1] << endl;
for (int i = 0; i < m; i++)//二维
{
delete[] c[i];//i行的列
delete[] b[i];
}
delete[]c;
delete[]b;
}
int main()
{
string s1 = { "ABCPDSFJGODIHJOFDIUSHGD" };
string s2 = { "OSDIHGKODGHBLKSJBHKAGHI" };
LCS(s1, s2);
return 0;
}
`在这里插入图片描述
本文代码思路来自:(代码和这位大佬的一样)
https://blog.csdn.net/weixin_40673608/article/details/84262695?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3.pc_relevant_default&utm_relevant_index=6