在看完《编程之美》一书的“计算字符串的相似度”一文后,对该书最后提出的问题作一点回忆与思考。
这里先将原问题再复述一遍:

原文算法代码
1 int calculateStringDistance(string strA, int pABegin, int pAEnd, string strB, int pBBegin, int pBEnd)
2 {
3 if(pABegin > pAEnd)
4 {
5 if(pBBegin > pBEnd)
6 return 0;
7 else
8 return pBEnd - pBBegin + 1;
9 }
10
11 if(pBBegin > pBEnd)
12 {
13 if(pABegin > pAEnd)
14 return 0;
15 else
16 return pAEnd - pABegin + 1;
17 }
18
19 if(strA[pABegin] == strB[pBBegin])
20 {
21 return calculateStringDistance(strA, pABegin+1, pAEnd, strB, pBBegin+1, pBEnd);
22 }
23 else
24 {
25 int t1 = calculateStringDistance(strA, pABegin, pAEnd, strB, pBBegin+1, pBEnd);
26 int t2 = calculateStringDistance(strA, pABegin+1, pAEnd, strB, pBBegin, pBEnd);
27 int t3 = calculateStringDistance(strA, pABegin+1, pAEnd, strB, pBBegin+1, pBEnd);
28 return minValue(t1, t2, t3) + 1;
29 }
30 }
上面的递归程序,有什么地方需要改进呢?问题在于:在递归的过程中,有些数据被重复计算了。
我们知道适合采用动态规划方法的最优化问题中的两个要素:最优子结构和重叠子问题。另外,还有一种方法称为备忘录(memoization),可以充分利用重叠子问题的性质。
下面简述一下动态规划的基本思想。和分治法一样,动态规划是通过组合子问题的解而解决整个问题的。我们知道,分治算法是指将问题划分 成一睦独立的子问题,递归 地求解各子问题,然后合并子问题的解而得到原问题的解。与此不同,动态规划适用于子问题不是独立 的情况,也就是各子问题包含公共的子子问题。在这种情况 下,若用分治法则会做许多不必要的工作,即重复地求解公共的子子问题。动态规划算法对每个子子问题只求解一次,将其结果保存在一张表中,从而避免每次遇到各个子问题时重新计算答案。
动态规划通常应用于最优化问题。此类问题可能有很多种可行解,每个解有一个值,而我们希望找出一个具有最优(最大或最小)值的解。称这样的解为该问题的“一个”最优解(而不是“确定的”最优解),因为可能存在多个取最优值的解。
动态规划算法的设计可以分为如下4个步骤:
1)描述最优解的结构。
2)递归定义最优解的值。
3)按自底向上的方式计算最优解的值。
4)由计算出的结果构造一个最优解。
第1~3步构成问题的动态规划解的基础。第4步在只要求计算最优解的值时可以略去。如果的确做了第4步,则有时要在第3步的计算中记录一些附加信息,使构造一个最优解变得容易。
该问题明显完全符合动态规划的两个要素,即最优子结构和重叠子问题特性。该问题的最优指的是两个字符串的最短距离,子问题的重叠性可以从原书中的那个递归算法中看出。
下面再来详细说说什么是重叠子问题。适用于动态规划求解的最优化问题必须具有的第二个要素是子问题的空间要“很小”,也就是用来解原问题的递归算法可以反复地解同样的子问题,而不是总在产生新的子问题。典型地,不同的子问题数是输入规模的一个多项式。当一个递归算法不断地调用同一问题时,我们说该最优问题包含重叠子问题。相反地,适合用分治法解决的问题只往往在递归的每一步都产生全新的问题。动态规划算法总是充分利用重叠子问题,即通过每个子问题只解一次,把解保存在一个需要时就可以查看的表中,而每次查表的时间为常数。
根据以上的分析,我写了如下的动态规划算法:

DP Algorithm
1 /*
2 * A loop method using dynamic programming.
3 * Calculate from bottom to top.
4 */
5 int calculateStringDistance(string strA, string strB)
6 {
7 int lenA = (int)strA.length();
8 int lenB = (int)strB.length();
9 int c[lenA+1][lenB+1]; // Record the distance of all begin points of each string
10
11 // i: begin point of strA
12 // j: begin point of strB
13 for(int i = 0; i < lenA; i++) c[i][lenB] = lenA - i;
14 for(int j = 0; j < lenB; j++) c[lenA][j] = lenB - j;
15 c[lenA][lenB] = 0;
16
17 for(int i = lenA-1; i >= 0; i--)
18 for(int j = lenB-1; j >= 0; j--)
19 {
20 if(strB[j] == strA[i])
21 c[i][j] = c[i+1][j+1];
22 else
23 c[i][j] = minValue(c[i][j+1], c[i+1][j], c[i+1][j+1]) + 1;
24 }
25
26 return c[0][0];
27 }
最后再说说“备忘录”法。其实它算是动态规划的一种变形,它既具有通常的动态规划方法的效率,又采用了一种自顶向下的策略。其思想就是备忘原问题的自然但低效的递归算法。像在通常的动态规划中一样,维护一个记录了子问题解的表,但有关填表动作的控制结构更像递归算法。
加了备忘的递归算法为每一个子问题的解在表中记录一个表项。开始时,每个表项最初都包含一个特殊的值,以表示该表项有待填入。当在递归算法的执行中第一次遇到一个子问题时,就计算它的解并填入表中。以后每次遇到该子问题时,只要查看并返回先前填入的值即可。
下面是原文递归算法的做备忘录版本,并通过布尔变量memoize来控制是否使用备忘录,以及布尔变量debug来控制是否打印调用过程。有兴趣的读都可以通过这两个布尔变量的控制来对比一下备忘录版本与非备忘录版本的复杂度。

备忘录版
1 #include <iostream>
2 #define M 100
3
4 using namespace std;
5
6 const bool debug = false; // Whether to print debug info
7 const bool memoize = true; // Whether to use memoization
8 unsigned int cnt = 0; // Line number for the debug info
9
10 int memoizedDistance[M][M]; // Matrix for memoiztion
11
12 int minValue(int a, int b, int c)
13 {
14 if(a < b && a < c) return a;
15 else if(b < a && b < c) return b;
16 else return c;
17 }
18
19 /*
20 * A recursive method which can be decorated by memoization.
21 * Calculate from top to bottom.
22 */
23 int calculateStringDistance(string strA, int pABegin, int pAEnd, string strB, int pBBegin, int pBEnd)
24 {
25 if(memoize && memoizedDistance[pABegin][pBBegin] >= 0)
26 return memoizedDistance[pABegin][pBBegin];
27
28 if(pABegin > pAEnd)
29 {
30 if(pBBegin > pBEnd)
31 {
32 if(memoize)
33 memoizedDistance[pABegin][pBBegin] = 0;
34 if(debug)
35 cout << cnt++ << ": m(" << pABegin << "," << pBBegin << ")=0" << endl;
36 return 0;
37 }
38 else
39 {
40 int temp = pBEnd - pBBegin + 1;
41 if(memoize)
42 memoizedDistance[pABegin][pBBegin] = temp;
43 if(debug)
44 cout << cnt++ << ": m(" << pABegin << "," << pBBegin << ")=" << temp << endl;
45 return temp;
46 }
47 }
48
49 if(pBBegin > pBEnd)
50 {
51 if(pABegin > pAEnd)
52 {
53 if(memoize)
54 memoizedDistance[pABegin][pBBegin] = 0;
55 if(debug)
56 cout << cnt++ << ": m(" << pABegin << "," << pBBegin << ")=0" << endl;
57 return 0;
58 }
59 else
60 {
61 int temp = pAEnd - pABegin + 1;
62 if(memoize)
63 memoizedDistance[pABegin][pBBegin] = temp;
64 if(debug)
65 cout << cnt++ << ": m(" << pABegin << "," << pBBegin << ")=" << temp << endl;
66 return temp;
67 }
68 }
69
70 if(strA[pABegin] == strB[pBBegin])
71 {
72 int temp = calculateStringDistance(strA, pABegin+1, pAEnd, strB, pBBegin+1, pBEnd);
73 if(memoize)
74 memoizedDistance[pABegin][pBBegin] = temp;
75 if(debug)
76 cout << cnt++ << ": m(" << pABegin << "," << pBBegin << ")=" << temp << endl;
77 return temp;
78 }
79 else
80 {
81 int t1 = calculateStringDistance(strA, pABegin, pAEnd, strB, pBBegin+1, pBEnd);
82 int t2 = calculateStringDistance(strA, pABegin+1, pAEnd, strB, pBBegin, pBEnd);
83 int t3 = calculateStringDistance(strA, pABegin+1, pAEnd, strB, pBBegin+1, pBEnd);
84 int temp = minValue(t1, t2, t3) + 1;
85 if(memoize)
86 memoizedDistance[pABegin][pBBegin] = temp;
87 if(debug)
88 cout << cnt++ << ": m(" << pABegin << "," << pBBegin << ")=" << temp << endl;
89 return temp;
90 }
91 }
92
93 int main()
94 {
95 if(memoize)
96 {
97 // initialize the matrix : memoizedDistance[][]
98 for(int i = 0; i < M; i++)
99 for(int j = 0; j < M; j++)
100 memoizedDistance[i][j] = -1; // -1 means unfilled cell yet
101 }
102
103 string strA = "abcdfef";
104 string strB = "a";
105
106 cout << endl << "Similarity = "
107 << 1.0 / (1 + calculateStringDistance(strA, 0, (int)strA.length()-1, strB, 0, (int)strB.length()-1))
108 << endl;
109
110 return 0;
111 }
总结 : 可以计算出,如果不用动态规划或是做备忘录,最坏情况下复杂度约为:lenA!*lenB!。使用动态规划的复杂度为O((lenA+1)*(lenB+1))。递归并做备忘录的方法最坏情况下复杂度为O((lenA+1)*(lenB+1))。
在实际应用中,如果所有的子问题都至少要被计算一次,则一个自底向上的动态规划算法通常要比一个自顶向下的做备忘录算法好出一个常数因子,因为前者无需递归的代价,而且维护表格的开销也小些。此外,在有些问题中,还可以用动态规划算法中的表存取模式来进一步减少时间或空间上的需求。或者,如果子问题空间中的某些子问题根本没有必要求解,做备忘录方法有着只解那些肯定要求解的子问题的优点,对于本问题就是这样。