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] =

5
return Lookup-Chain(p, 1, n)

Lookup-Chain(p, i, j)

1
if m[i,j] <

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
entries is initialized once (line
4) and is filled in by one call to Lookup-Chain.

Each of calls to Lookup-Chain takes n steps ignoring recursion, so the total time required is .

The algorithm requires memory.