Consider how the longest common subsequence problem is decomposed into sub-problems, set a= "A0,a1,...,am-1", b= "b0,b1,...,bn-1", and z= "Z0,z1,...,zk-1" as their longest common subsequence. It is not difficult to prove the following properties:
(1) If am-1=bn-1, then zk-1=am-1=bn-1, and "Z0,z1,...,zk-2" is a "a0,a1,...,am-2" and "b0,b1,...,bn-2" a longest common sub-sequence;
(2) If the am-1!=bn-1, if the zk-1!=am-1, the implication "z0,z1,...,zk-1" is "a0,a1,...,am-2" and "b0,b1,...,bn-1" a longest common sub-sequence;
(3) If am-1!=bn-1, then if zk-1!=bn-1, implication "z0,z1,...,zk-1" is a "a0,a1,...,am-1" and "b0,b1,...,bn-2" a longest common sub-sequence.
The problem is written in a recursive style:
Backtracking outputs the longest common subsequence process:
Packagetest;Importjava.util.ArrayList;Importjava.util.List;/*** @ClassName: LCS * @Description: TODO *@author: * @Date: 2015-06-29 12:50:14*/ Public classLCS {Static intmax=2; Public StaticList<string> Getlcs (int[] C,intIintj, string X, String y) {List<String> T =NewArraylist<string>(); if(i = = 0 | | j = 0){ ; }Else if(C[i][j] = = 1) {T= Getlcs (c,i-1,j-1, x, y); if(t.size () = = 0) T.add (""); for(intk = 0; K < T.size (); k++) {String v=T.get (k); if(V.length () > 0){ intit = Integer.parseint (v.substring (V.lastindexof (") +1,v.lastindexof (", "))); if(I-it > 2) {t.remove (k); Continue; } intJT = Integer.parseint (v.substring (V.lastindexof (",") +1,v.lastindexof (")"))); if(J-jt > 2) {t.remove (k); Continue; }} t.set (K, T.get (k)+ X.charat (i) + "(" +i+ "," +j+ ")"); } }Else if(C[i][j] = = 2) {T= Getlcs (c,i-1, J,x,y); }Else if(C[i][j] = = 3) {T.addall (Getlcs (c,i-1, j,x,y)); T.addall (Getlcs (c,i,j-1, x, y)); }Else{T= Getlcs (c,i,j-1, x, y); } returnT; } Public Static intLcslength (int[] C,intIintJbyte[] xx,byte[] yy,int[] max) { if(i = = 0 | | j = 0) {C[i][j]= 0; }Else if(Xx[i] = =Yy[j]) {Max[i][j]= 1; C[I][J]= Lcslength (C,i-1,j-1,xx,yy,max) +1; }Else { intII = lcslength (c,i-1, J,xx,yy,max); intJJ = Lcslength (c,i,j-1, Xx,yy,max); if(ii >JJ) Max[i][j]= 2; Else if(ii = =JJ) Max[i][j]= 3; C[I][J]=Math.max (II,JJ); } returnC[i][j]; } Public Static voidMain (string[] args) {String x= "Abcbdab"; String y= "Bdcaba"; byte[] xx =x.getbytes (); byte[] yy =y.getbytes (); intC[][] =New int[X.length ()][y.length ()]; intMax[][] =New int[X.length ()][y.length ()]; System.out.println (Lcslength (C,x.length ()-1,y.length ()-1, Xx,yy,max)); List<String> list = Getlcs (Max,x.length () -1,y.length ()-1, x, y); for(String v:list) System.out.println (v); System.out.print ("\ n"); for(intj = 1; J < Y.length (); j + +) System.out.print (Y.charat (j)+ " "); System.out.println (""); for(inti = 1; I < x.length (); i++) {System.out.print (X.charat (i)+ " "); for(intj = 1; J < Y.length (); j + +) System.out.print (C[i][j]+ " "); System.out.println (" "); } }}
The longest common subsequence--dynamic programming algorithm