the problem i am facing in the longest subsequence: For Ex:
“ABCDGH” and “AEDFHR” is “ADH” of length 3
Code:
void lcs( char *X, char *Y, int m, int n )
{
int L[m+1][n+1];
/* Following steps build L[m+1][n+1] in bottom up fashion. Note
that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
I don't understand why this line of code:
L[i][j] = max(L[i-1][j], L[i][j-1]);
What if i want to print the sequence ie ADH
how can i do that?
I don't understand why this line of code:
L[i][j] = max(L[i-1][j], L[i][j-1]);
If the last character of X[0..i-1]
does not match the last character of Y[0..j-1]
, then for every common subsequence at least one of these characters does not belong. The answer thus is given by the maximum length for X[0..i-2]
and Y[0..j-1]
, or the maximum length for X[0..i-1]
and Y[0..j-2]
.
To recover the actual subsequence, we have to trace back these decisions like so.
char lcs[min(m, n) + 1];
char *end = lcs;
int i = m;
int j = n;
while (i > 0 && j > 0) {
if (X[i - 1] == Y[j - 1]) {
*end = X[i - 1];
end++;
i--;
j--;
} else if (L[i - 1][j] >= L[i][j - 1]) {
i--;
} else {
j--;
}
}
reverse(lcs, end);
*end = '\0';
puts(lcs);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.