用动态规划实现矩阵连乘问题的代码
时间: 2024-05-02 17:14:28 浏览: 108
动态规划是解决矩阵连乘问题的常用方法。下面是一个用动态规划实现矩阵连乘问题的代码示例:
```python
def matrix_chain_order(p):
n = len(p) - 1
m = [[0] * (n+1) for _ in range(n+1)]
s = [[0] * (n+1) for _ 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`函数用于计算最优的矩阵连乘顺序,并返回最优值矩阵`m`和最优断点矩阵`s`。`print_optimal_parens`函数用于打印最优的矩阵连乘顺序。
阅读全文