请给出动态规划算法矩阵连乘问题的代码
时间: 2023-10-31 12:04:12 浏览: 86
利用动态规划算法实现矩阵连乘 .zip_C#
5星 · 资源好评率100%
下面是动态规划算法矩阵连乘问题的代码实现(Python):
```python
def matrix_chain_order(p):
n = len(p) - 1
m = [[0] * (n+1) for i in range(n+1)]
s = [[0] * (n+1) for i in range(n+1)]
for l in range(2, n+1):
for i in range(1, n-l+2):
j = i + l - 1
m[i][j] = float("inf")
for k in range(i, j):
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
if q < m[i][j]:
m[i][j] = q
s[i][j] = k
return m, s
def print_optimal_parens(s, i, j):
if i == j:
print("A" + str(i), end="")
else:
print("(", end="")
print_optimal_parens(s, i, s[i][j])
print_optimal_parens(s, s[i][j] + 1, j)
print(")", end="")
p = [30, 35, 15, 5, 10, 20, 25]
m, s = matrix_chain_order(p)
print_optimal_parens(s, 1, len(p)-1)
```
其中,`matrix_chain_order(p)`函数计算最小代价矩阵m和分割点矩阵s,`print_optimal_parens(s, i, j)`函数输出最优加括号方案。
阅读全文