還是動態規劃.還是動態規劃.寫出來了,比較順手.
// LCSLenth.cpp -- 2011-06-17-23.05<br />#include "stdafx.h"<br />#include <iostream><br />#include <cstring></p><p>enum {Direction_Left, Direction_Up, Direction_TopLeft} ;</p><p>char * * LCSLenth (const char * const strA, const char * const strB) ;<br />void printLCS (const char * const * const recordDirection, const char * const strA, const int i, const int j) ;</p><p>int _tmain(int argc, _TCHAR* argv[])<br />{<br />char * strA = " ABCBDAB", * strB = " BDCABA" ;<br />char * * recordDirection = LCSLenth (strA, strB) ;</p><p>printLCS(recordDirection, strA, strlen(strA) - 1, strlen(strB) - 1) ;<br />for (unsigned int i = 0; i < strlen(strA); ++i)<br />delete []recordDirection[i] ;<br />delete []recordDirection ;</p><p>return 0 ;<br />}</p><p>//Assume imports two strings, first position of each string dosen't storage character.<br />char * * LCSLenth (const char * const strA, const char * const strB)<br />{<br />int aSize = strlen(strA) ;<br />int * * recordLenth = new int *[aSize] ;<br />char * * recordDirection = new char *[aSize] ;<br />int bSize = strlen(strB) ;<br />for (int i = 0; i < aSize; ++i)<br />{<br />recordLenth[i] = new int[bSize] ;<br />recordDirection[i] = new char[bSize] ;<br />}<br />for (int i = 0; i < aSize; ++i)<br />recordLenth[i][0] = 0 ;<br />for (int i = 0; i < bSize; ++i)<br />recordLenth[0][i] = 0 ;<br />for (int i = 1; i < aSize; ++i)<br />{<br />for (int j = 1; j < bSize; ++j)<br />{<br />if (strA[i] == strB[j])<br />{<br />recordLenth[i][j] = recordLenth[i - 1][j - 1] + 1 ;<br />recordDirection[i][j] = Direction_TopLeft ;<br />}<br />else if (recordLenth[i - 1][j] >= recordLenth[i][j - 1])<br />{<br />recordLenth[i][j] = recordLenth[i - 1][j] ;<br />recordDirection[i][j] = Direction_Up ;<br />}<br />else<br />{<br />recordLenth[i][j] = recordLenth[i][j - 1] ;<br />recordDirection[i][j] = Direction_Left ;<br />}<br />}<br />}<br />for (int i = 0; i < aSize; ++i)<br />delete []recordLenth[i] ;<br />delete []recordLenth ;</p><p>return recordDirection ;<br />}</p><p>void printLCS (const char * const * const recordDirection, const char * const strA, const int i, const int j)<br />{<br />if (0 == i || 0 == j)<br />return ;<br />if (Direction_TopLeft == recordDirection[i][j])<br />{<br />printLCS(recordDirection, strA, i - 1, j - 1) ;<br />std ::cout << strA[i] ;<br />}<br />else if (Direction_Left == recordDirection[i][j])<br />printLCS(recordDirection, strA, i, j - 1) ;<br />else<br />printLCS(recordDirection, strA, i - 1, j) ;<br />}