Matrix chain multiplication: Difference between revisions

Content added Content deleted
m (→‎{{header|zkl}}: added test case)
Line 555: Line 555:


=== Iterative solution ===
=== Iterative solution ===
In the previous solution, memoization is done blindly with a dictionary. However, we need to compute the optimal products for all sublists. A sublist is described by its first index and length (resp. i and j+1 in the following function), hence the set of all sublists can be descibed by the indices of elements in a triangular array u. We first fill the "solution" (there is not product) for sublists of length 1 (u[0]), then for each successive length we optimize using what when know about smaller sublists. Instead of keeping track of the optimal solutions, the single needed one is computed in the end.
In the previous solution, memoization is done blindly with a dictionary. However, we need to compute the optimal products for all sublists. A sublist is described by its first index and length (resp. i and j+1 in the following function), hence the set of all sublists can be descibed by the indices of elements in a triangular array u. We first fill the "solution" (there is no product) for sublists of length 1 (u[0]), then for each successive length we optimize using what when know about smaller sublists. Instead of keeping track of the optimal solutions, the single needed one is computed in the end.


<lang python>def optim4(a):
<lang python>def optim4(a):