dp = [[0] * (N + 1) for _ in range(N + 1)]
for l in range(2, N + 1):
for i in range(N - l + 1):
j = i + l
for k in range(i, j):
val = f(val, g(dp[i][k], dp[k][j], i, j, k))
dp[i][j] = val
return dp[0][N]
dp = [[0] * N for _ in range(N)]
for l in range(1, N):
for i in range(N - l):
j = i + l
for k in range(i, j):
val = f(val, g(dp[i][k], dp[k + 1][j], i, j, k))
dp[i][j] = val
return dp[0][N - 1]
for l in range(1, n):
for i in range(n - l):
j = i + d
m = sizes[i][0] * sizes[j][1]
dp[i][j] = min(dp[i][k] + dp[k + 1][j] + m * sizes[k][0] for k in range(i, j))
for l in range(1, n):
for i in range(n - l):
j = i + l
tmp = sizes[i][0] * sizes[j][1]
min_ij = min(dp_ik + dp_jk + tmp * sz_k[0]
for dp_ik, dp_jk, sz_k
in zip(dp[i][i:j], dp[j][i + 1:j + 1], sizes[i + 1:j + 1]))
dp[i][j] = dp[j][i] = min_ij
"""Knuth Optimization"""
dp = [[0] * N for _ in range(N + 1)]
opt = [[0] * N for _ in range(N)]
for i in range(N):
opt[i][i] = i
for l in range(1, N):
for i in range(N - l):
j = i + l
dp[i][j], opt[i][j] = min((dp[i][k] + dp[k + 1][j], k)
for k in range(opt[i][j - 1], opt[i + 1][j] + 1))
dp[i][j] += C[i][j]
return dp[0][size - 1]
"""Knuth Optimization (Optimized)"""
dp = [[0] * size for _ in range(N + 1)]
opt = list(range(N))
for l in range(1, N):
for i in range(N - l):
j = i + l
dp[i][j], opt[i] = min((dp[i][k] + dp[k + 1][j], k)
for k in range(opt[i], opt[i + 1] + 1))
dp[i][j] += C[i][j]
return dp[0][size - 1]