@@ -18,13 +18,24 @@ func main() {
1818 d2 := LCS (str1 , str2 , l1 , l2 )
1919 printLCS (d2 , str1 , l1 , l2 )
2020 fmt .Println ("\n end" )
21+ // 设序列X=< x1, x2, …, xm >和Y=< y1, y2, …, yn >的一个最长公共子序列Z=< z1, z2, …, zk >,则:+
22+
23+ // 若xm=yn,则zk=xm=yn且Zk-1是Xm-1和Yn-1的最长公共子序列;
24+ // 若xm≠yn且zk≠xm ,则Z是Xm-1和Y的最长公共子序列;
25+ // 若xm≠yn且zk≠yn ,则Z是X和Yn-1的最长公共子序列。
26+ // 其中Xm-1 = < x1, x2, …, xm-1 >,Yn-1 = < y1, y2, …, yn-1 >,Zk-1 = < z1, z2, …, zk-1 >
2127}
2228
2329func LCS (str1 string , str2 string , l1 int , l2 int ) [10 ][10 ]int {
2430
2531 var d1 [10 ][10 ]int //make([][]int, 10, 10)
2632 var d2 [10 ][10 ]int //make([][]int, 10, 10)
2733
34+ // i= 0 j=0 len = 0 return 0
35+ if i == 0 || j == 0 {
36+ return d2
37+ }
38+
2839 for i := 0 ; i < l1 ; i ++ {
2940 d1 [i ][0 ] = 0
3041 }
@@ -34,15 +45,19 @@ func LCS(str1 string, str2 string, l1 int, l2 int) [10][10]int {
3445
3546 for i := 1 ; i <= l1 ; i ++ {
3647 for j := 1 ; j <= l2 ; j ++ {
48+ //x[i] == y[j]
3749 if str1 [i - 1 ] == str2 [j - 1 ] {
3850 d1 [i ][j ] = d1 [i - 1 ][j - 1 ] + 1
39- d2 [i ][j ] = 1
40- } else if d1 [i - 1 ][j ] >= d1 [i ][j - 1 ] {
41- d1 [i ][j ] = d1 [i - 1 ][j ]
42- d2 [i ][j ] = 3
51+ d2 [i ][j ] = 1 //对角线
4352 } else {
44- d1 [i ][j ] = d1 [i ][j - 1 ]
45- d2 [i ][j ] = 2
53+ //max (c[i,j-1],c[i-1],j)
54+ if d1 [i - 1 ][j ] >= d1 [i ][j - 1 ] {
55+ d1 [i ][j ] = d1 [i - 1 ][j ]
56+ d2 [i ][j ] = 3 //上方
57+ } else {
58+ d1 [i ][j ] = d1 [i ][j - 1 ]
59+ d2 [i ][j ] = 2 //左边
60+ }
4661 }
4762 }
4863 }
@@ -58,9 +73,11 @@ func LCS(str1 string, str2 string, l1 int, l2 int) [10][10]int {
5873
5974func printLCS (b [10 ][10 ]int , str1 string , i int , j int ) {
6075
76+ //递归结束条件
6177 if i < 0 || j < 0 {
6278 return
6379 }
80+
6481 fmt .Println (i , j )
6582 if b [i ][j ] == 1 {
6683 printLCS (b , str1 , i - 1 , j - 1 )
0 commit comments