算法分类:
动态规划
算法原理:
如果i和j都大于0,那么
若ai=bj,L[i, j] = L[i-1][j-1] + 1;
若ai<>bj,L[i, j] = max{ L[i-1][j], L[i][j-1] }
算法时空复杂度:
时间复杂度:(theta)(mn)
习题地址:
hdu1159
代码实现:
/*
* HDU 1159 Common Subsequence
* 最长公共子序列问题: 动态规划
*
* 递归公式:
* L[i,k] = 0 (i=0 或j=0)
* = L[i-1][j-1]+1 (i>0,j>0,ai=bj)
* = max{L[i,j-1],L[i-1,j]} (i>0,j>0,ai<>bj)
*/
#include <iostream>
using namespace std;
const int N = 10005;
int L[N][N];
char a[N],b[N];
int main()
{
while (scanf("%s%s",a,b)!=EOF) {
int lena = strlen(a);
int lenb = strlen(b);
for (int i = 0; i <= lena; ++ i)
L[i][0] = 0;
for (int i = 0; i <= lenb; ++ i)
L[0][i] = 0;
for (int i = 1; i <= lena; ++ i) {
for (int j = 1; j <= lenb; ++ j) {
if (a[i-1] == b[j-1]) {
L[i][j] = L[i-1][j-1] + 1;
} else {
L[i][j] = L[i-1][j]>L[i][j-1]?L[i-1][j]:L[i][j-1];
}
}
}
printf("%d\n",L[lena][lenb]);
}
}