p = [30, 35, 15, 5, 10, 20, 25]
def matrix_chain_order(p):
n = len(p) - 1 # 矩阵个数
m = [[0 for i in range(n)] for j in range(n)]
s = [[0 for i in range(n)] for j in range(n)] # 用来记录最优解的括号位置
for l in range(1, n): # 控制列,从左往右
for i in range(l-1, -1, -1): # 控制行,从下往上
m[i][l] = float('inf') # 保存要填充格子的最优值
for k in range(i, l): # 控制分割点
q = m[i][k] + m[k+1][l] + p[i]*p[k+1]*p[l+1]
if q < m[i][l]:
m[i][l] = q
s[i][l] = k
return m, s
def print_option_parens(s, i, j):
if i == j:
print('A'+str(i+1), end='')
else:
print('(', end='')
print_option_parens(s, i, s[i][j])
print_option_parens(s, s[i][j]+1, j)
print(')', end='')
r, s = matrix_chain_order(p)
print_option_parens(s, 0, 5)
代码遇到的坑
m = [[0 for i in range(n)] for j in range(n)]其实最先的定义方式为m=[[0] * n ] * n,但是这样会产生一个很严重的问题