Recursive type:
Example plots:
Code:
1#include <stdio.h>2#include <string.h>3 Const intn=111;4 intDp[n][n],f[n][n];5 CharA[n],b[n],c[n];6 voidLCS (Char*a,Char*b,intLaintlb)7 {8 inti,j;9Memset (DP,0,sizeof(DP));Ten for(i=1; i<=la;i++) One { A for(j=1; j<=lb;j++) - { - if(a[i-1]==b[j-1]) the { -dp[i][j]=dp[i-1][j-1]+1; -f[i][j]=0; - } + Else if(dp[i-1][j]>dp[i][j-1]) - { +dp[i][j]=dp[i-1][j]; Af[i][j]=-1; at } - Else - { -dp[i][j]=dp[i][j-1]; -f[i][j]=1; - } in } - } to } + voidDfsChar*s,intIintj) - { the if(!i| |! Jreturn ; * if(!F[i][j]) $ {Panax NotoginsengDFS (s,i-1, J-1); -printf"%c", s[i-1]); the } + if(f[i][j]==1) ADFS (s,i,j-1); the if(f[i][j]==-1) +DFS (s,i-1, j); - } $ intMain () $ { - while(SCANF ("%s%s", A, b)! =EOF) - { the intLa=strlen (a), lb=strlen (b); - LCS (a,b,la,lb);Wuyiprintf"The longest common sub-sequence for%s and%s is: \ n", A, b); the DFS (A,LA,LB); -Puts""); Wuprintf"Length:%d\n", dp[la][lb]); - } About return 0; $}
Reference article: http://blog.csdn.net/yysdsyl/article/details/4226630
Longest common sub-sequence template (LCS) template