问题描述:给定两个字符串str1和str2,返回两个字符串的最长公共子序列,例如:str1 = “1A2C3D4B56”,str2 =  "D23CA45B6A",,“123456”或者“12C4B6”都是最长公共子序列,返回哪一个都行。

如果str1的长度为M,str2的长度为N,生成M*N的矩阵dp。dp[i][j]的含义是str1[0...i]与str2[0...j]的最长公共子序列。

 

int dp[1005][1005] = { 0 };
int lcs(string str1,string str2)
{
	int l1 = str1.size();
	int l2 = str2.size();
	

	for (int i = 1; i <= l1; i++)
		for (int j = 1; j <= l2; j++)
			if (str1[i - 1] == str2[j - 1])
				dp[i][j] = dp[i - 1][j - 1] + 1;
			else dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);

	return dp[l1][l2];
}