最長公共子串行(LCS)

2021-07-22 06:56:07 字數 1170 閱讀 3074

int lcs(char *t, char *p, int n, int m)

}

通過犧牲記憶體換取速度

// 返回長度值

int lcs2(char *t, char *p, int n, int m)

for(int i=1;iarray[i]= 0;

}for(int i=1; i1;i++)

else}}

int result = array[m*n-1];

char *output = new

char[result];

//回溯輸出子串行

backtrack(t, array, n, m, output, result);

//此處輸出lcs的一種可能的結果

printf("%s", output);

delete output ;

delete array;

return result ;

}

回溯輸出最長的公共子串行

void backtrack(char *t, int *array, int n, int m, char *output, int lcs_len)

else

if (array[i*m + j] == array[(i - 1)*m + j])

i--;

else

}}

如果只需要輸出lcs的長度,不需要輸出lcs可能的值,可以用空間壓縮的方法將額外的空間減少為o

int lcs3(char * t, char *p, int n, int

m) for (int j = 0; j < m; j++)

int flag1 = 1;

int flag2 = 0;

for (int i = 0; i < n-1; i++)

else

}flag1 = flag2;

flag2 = -flag2 + 1;

}int rerult = listp[flag2*m + m - 1];

delete listt;

delete listp;

return rerult;

}

LCS 最長公共子串行

問題描述 我們稱序列z z1,z2,zk 是序列x x1,x2,xm 的子串行當且僅當存在嚴格上 公升的序列 i1,i2,ik 使得對 j 1,2,k,有 xij zj。比如z a,b,f,c 是 x a,b,c,f,b,c 的子串行。現在給出兩個序列 x和 y,你的任務是找到 x和 y的最大公共子...

LCS最長公共子串行

求兩個字串的最大公共子串行問題 子串行的定義 若給定序列x 則另一串行z 是x的子串行是指存在乙個嚴格遞增下標序列使得對於所有j 1,2,k有 zj xij。例如,序列z 是序列x 的子序列,相應的遞增下標序列為。分析 用動態規劃做 1.最長公共子串行的結構 事實上,最長公共子串行問題具有最優子結構...

LCS最長公共子串行

lcs是longest common subsequence的縮寫,即最長公共子串行。乙個序列,如果是兩個或多個已知序列的子串行,且是所有子串行中最長的,則為最長公共子串行。複雜度對於一般的lcs問題,都屬於np問題。當數列的量為一定的時,都可以採用動態規劃去解決。解法動態規劃的乙個計算最長公共子串...