Problem description
A subsequence of a sequence is a new sequence formed from the initial sequence by removing some elements but not destroying the relative positions of the remaining elements.
Given two sequences X and Y, if z is both a subsequence of X and a subsequence of Y, then z is the public subsequence of X and Y.
Given two sequences x = {x1, x2. .., xm} and Y = {y1, y2. .. yn}, find the z = {z0, Z1 ,..., ZK} is their longest common subsequence.
Optimal sub-structure
Set x = {x1, x2. .., xm} and Y = {y1, y2. .. yn} as two sequences. z = {z0, Z1 ,..., ZK} is any LCS.
1) if XM = ym, then zk = XM = ym, And the Zk-1 is an lcs of the Xm-1 and Yn-1.
2) If XM! = Ym & ZK! = XM, then z is an lcs of the Xm-1 and Y.
3) If XM! = Ym & ZK! = YN, then z is an LCS of x and Yn-1.
State transition equation
C [I, j] is the length of an LCS of sequence XI and Yi.
Code Implementation
// LCS # include <iostream> # include <string> using namespace STD; void lcs_length (string X, string y, INT (* C) [100], INT (* B) [1, 100]) {int M, N; M = x. length (); n = x. length (); int I, j; // if I or J is equal to 0, C [I] [J] = 0; for (I = 1; I <= m; I ++) {C [I] [0] = 0 ;}for (I = 1; I <= N; I ++) {c [0] [I] = 0;} // traverses two strings and marks C [I] [J] in sequence. c [I] [J] indicates the length of LCS from X to I and from // y to J. // array B indicates the longest value. the route of the Public substring, this route is the corresponding letter for (I = 1; I <= m; I ++) {for (j = 1; j <= N; j ++) {If (X [I-1] = Y [J-1]) {C [I] [J] = C [I-1] [J-1] + 1; // place the arrow at the top left of B [I] [J] = 1;} else {If (C [I] [J-1]> = C [I-1] [J]) {c [I] [J] = C [I] [J-1]; // The arrows represent the left B [I] [J] = 2 ;} else {C [I] [J] = C [I-1] [J]; // an arrow pointing up B [I] [J] = 3 ;}}}}} void printanswer (string X, INT (* B) [100], int I, Int J) {if (I = 0 | j = 0) {return ;} else {If (B [I] [J] = 1) {printanswer (X, B, I-1, J-1); cout <X [I-1] <"";} else if (B [I] [J] = 2) {printanswer (X, B, I, J-1);} else {printanswer (X, B, I-1, j) ;}}int main () {string x = "abcbda"; string y = "bdcaba"; int C [100] [100] = {0 }; int B [100] [100] = {0}; lcs_length (X, Y, C, B); cout <"the LCS is:" <C [X. length ()] [Y. length ()] <Endl; printanswer (X, B, X. length (), Y. length (); Return 0 ;}
Reference: Longest Common substring LCS code implementation-http://blog.csdn.net/liuzhanchen1987/article/details/7851413