备忘录是动态规划算法的变形﹒备忘录方法也是用表格保存已解决子问题的答案﹒
与动态规划算法不同的是,备忘录方法的递归方式是自顶向下的,而动态规划算法则是自底向上递归的.因此,备忘录方法的控制结构与直接递归方法的控制结构相同,而区别在于备忘录方法为每个解过的子问题建立了备忘录以备需要时查看,避免了相同子问题的重复求解.
备忘录方法为每个子问题建立一个记录项,并初始化为一个特殊值表示该子问题尚未求解﹒在求解过程中,对每个待求的子问题,首先查看其相应的记录项,如若记录项仍为初始化时的特殊值,则表示该子问题尚未求解,于是对其求解﹔如若记录项非特殊值,则表示该子问题已求解,直接取值即可.
也就是备忘录就是不去调用已经算好的值也直接在去算一次
#include"stdafx.h"
#include<iostream>
using namespace std;
int RecurMatrixChain(int, int);
int p[7] = { 30, 35, 15, 5, 10, 20, 25 };
int m[7][7];
int s[7][7];
int MemoizeMatrixChain(int N){
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
m[i][j] = 0;
return RecurMatrixChain(1, N);
}
}
int RecurMatrixChain(int i, int j){
if (i == j)
return 0;
int v = RecurMatrixChain(i, i) + RecurMatrixChain(i + 1, j) + p[i - 1] * p[i] * p[j];
s[i][j] = i;
for (int k = i + 1; k < j; k++)
{
int t = RecurMatrixChain(i, k) + RecurMatrixChain(k + 1, j) + p[i - 1] * p[k] * p[j];
if (t < v)
{
v = t;
s[i][j] = k;
}
}
m[i][j] = v;
return v;
}
void prin(int i, int j)
{
if (i == j)
{
cout << "A" << i;
}
else
{
cout << "(";
prin(i, s[i][j]);
prin(s[i][j] + 1, j);
cout << ")";
}
//cout << "(A" << i << " A" << j << ")" << endl;
/*cout << "Multiply A " << i << ", " << s[i][j];
cout << " and A " << (s[i][j] + 1) << ", " << j << endl;*/
}
int main(){
//cout << RecurMatrixChain(1, 6) << endl;
cout << MemoizeMatrixChain(6) << endl;
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= 6; j++)
{
cout << m[i][j] << " ";
}
cout << endl;
}
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= 6; j++)
{
cout << s[i][j] << " ";
}
cout << endl;
}
prin(1, 6);
system("pause");
return 0;
}