请给出动态规划算法矩阵连乘问题的代码
时间: 2023-10-31 21:04:12 浏览: 88
动态规划矩阵连乘代码实现
下面是动态规划算法矩阵连乘问题的代码实现(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)`函数输出最优加括号方案。
阅读全文