動態規劃的備忘錄方法.這是我第一次使用備忘錄方法,說白了就是遞迴地調用,之後保留一個表,導致沒有重複的調用出現.很不錯.
// memoizedLCSLenth.cpp -- 2011-06-18-02.57<br />#include "stdafx.h"<br />#include <iostream><br />#include <cstring></p><p>const int EMPTY = -1 ;</p><p>void LCSLenth (const char * const strA, const char * const strB) ;<br />int subProgram (int * const * const memoized, const char * const strA, const char * const strB, const int i, const int j) ;<br />void introductionToAlgorithms15_4_2 (const int * const * const memoized, const char * const strA, const char * const strB, const int i, const int j) ;</p><p>int _tmain(int argc, _TCHAR* argv[])<br />{<br />char * strA = " ABCBDAB", * strB = " BDCABA" ;</p><p>LCSLenth(strA, strB) ;</p><p>return 0;<br />}</p><p>//Assume imports two strings, first position of each string dosen't storage character.<br />void LCSLenth (const char * const strA, const char * const strB)<br />{<br />int aSize = strlen(strA) ;<br />int * * memoized = new int *[aSize] ;<br />int bSize = strlen(strB) ;<br />for (int i = 0; i < aSize; ++i)<br />memoized[i] = new int[bSize] ;<br />for (int i = 0; i < aSize; ++i)<br />{<br />for (int j = 0; j < bSize; ++j)<br />memoized[i][j] = EMPTY ;<br />}<br />subProgram(memoized, strA, strB, aSize - 1, bSize - 1) ;<br />introductionToAlgorithms15_4_2(memoized, strA, strB, aSize - 1, bSize - 1) ;<br />for (int i = 0; i < aSize; ++i)<br />delete []memoized[i] ;<br />delete []memoized ;<br />}</p><p>int subProgram (int * const * const memoized, const char * const strA, const char * const strB, const int i, const int j)<br />{<br />if (0 == i || 0 == j)<br />{<br />if (EMPTY == memoized[i][j])<br />memoized[i][j] = 0 ;<br />}<br />else if (strA[i] == strB[j])<br />{<br />if (EMPTY == memoized[i - 1][j - 1])<br />memoized[i - 1][j - 1] = subProgram(memoized, strA, strB, i - 1, j - 1) ;<br />memoized[i][j] = memoized[i - 1][j - 1] + 1 ;<br />}<br />else<br />{<br />if (EMPTY == memoized[i - 1][j])<br />memoized[i - 1][j] = subProgram(memoized, strA, strB, i - 1, j) ;<br />if (EMPTY == memoized[i][j - 1])<br />memoized[i][j - 1] = subProgram(memoized, strA, strB, i, j - 1) ;<br />memoized[i][j] = memoized[i - 1][j] >= memoized[i][j - 1] ? memoized[i - 1][j] : memoized[i][j - 1] ;<br />}</p><p>return memoized[i][j] ;<br />}</p><p>void introductionToAlgorithms15_4_2 (const int * const * const memoized, const char * const strA, const char * const strB, const int i, const int j)<br />{<br />if (0 == i || 0 == j)<br />return ;<br />if (strA[i] == strB[j])<br />{<br />introductionToAlgorithms15_4_2(memoized, strA, strB, i - 1, j - 1) ;<br />std ::cout << strA[i] ;<br />}<br />else if (memoized[i - 1][j] >= memoized[i][j - 1])<br />introductionToAlgorithms15_4_2(memoized, strA, strB, i - 1, j) ;<br />else<br />introductionToAlgorithms15_4_2(memoized, strA, strB, i, j - 1) ;<br />}