next up previous
Next: Up: Previous:

Memoization

Top-Down recursive solution that remembers intermediate results.

For example, intermediate results found in m[2,4] are useful in determining the value of m[1,3].

Memoized-Matrix-Chain(p)
1
$\;\;\;\;\;$n = length(p) - 1
2
$\;\;\;\;\;$for i = 1 to n
3
$\;\;\;\;\;$ $\;\;\;\;\;$for j = i to n
4
$\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$m[i,j] = $\infty$
5
$\;\;\;\;\;$return Lookup-Chain(p, 1, n)

Lookup-Chain(p, i, j)
1
$\;\;\;\;\;$if m[i,j] <$\infty$
2
$\;\;\;\;\;$then return m[i,j]
3
$\;\;\;\;\;$if i = j
4
$\;\;\;\;\;$then m[i,j] = 0
5
$\;\;\;\;\;$else for k = i to j-1
6
$\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$q = Lookup-Chain(p, i, k) +
$\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$Lookup-Chain(p, k+1, j) + P[i-1]P[k]P[j]
7
$\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$if q < m[i,j]
8
$\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$then m[i,j] = q
9
$\;\;\;\;\;$return m[i,j]



In this algorithm each of $\Theta(n^2)$ entries is initialized once (line 4) and is filled in by one call to Lookup-Chain.

Each of \(\Theta(n^2)\) calls to Lookup-Chain takes n steps ignoring recursion, so the total time required is \(\Theta(n^2) * O(n) \;=\; O(n^3)\).

The algorithm requires \(\Theta(n^2)\) memory.


next up previous
Next: Up: Previous: