您的位置:首页 > 产品设计 > UI/UE

LintCode Longest Common Subsequence(最长公共子序列长度,动态规划入门题)

2017-09-10 15:25 453 查看
题目Link:http://www.lintcode.com/en/problem/longest-common-subsequence/

递推公式:



#include <iostream>
#include <cstring>

using namespace std;

class Solution {
public:
/**
* @param A, B: Two strings.
* @return: The length of longest common subsequence of A and B.
*/
int longestCommonSubsequence(string A, string B) {
// write your code here
//得出两个字符串的长度,如果长度为0直接返回0
int lenA = A.length();
int lenB = B.length();
if(lenA == 0 && lenA == lenB)
return 0;
//再字符串头添加空位,方便之后编码从1开始
A = " " + A;
B = " " + B;
int chess[lenA + 1][lenB + 1];
//将表中所有元素置为0
memset(chess, 0, sizeof(int) * lenA * lenB);
for (int i = 1; i <= lenA; i++) {
for (int j = 1; j <= lenB; j++) {
//当两个字符串中 A[i] == A[j],
// 则最长LCS = LCS{(A[i - 1], A[j- 1])} + 1
//否则就在LCS{(A[i - 1], A[j])},和 LCS{(A[i], A[j- 1])}中选最长的那个
//这里的A[i],A[j]均指的是字符串
if (A[i] == B[j]) {
chess[i][j] = chess[i - 1][j - 1] + 1;
} else {
chess[i][j] = max(chess[i - 1][j], chess[i][j - 1]);
}
}
}
return chess[lenA][lenB];
}
};

int main() {

Solution slo;
string str1 = "";
string str2 = "";
cout << slo.longestCommonSubsequence(str1, str2) << endl;
return 0;
}


以上是AC代码,至于怎么得到最长公共子序列,可以从chess[lenA][lenB]开始回溯(Traceback),得到LCS。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息