# step是所有16×16的二维数组,step0是1×16的一维数组 n = len(step) dp = [[[0for _ inrange(16)] for _ inrange(16)] for _ inrange(15)] # prev的目的:获取最小值的每一轮选择 prev = [[[Nonefor _ inrange(16)] for _ inrange(16)] for _ inrange(15)]
for i inrange(16): for j inrange(16): dp[0][i][j] = step0[i] * step1[i][j]
for n inrange(1, 15): for i inrange(16): min_val_col = 100 row_of_min_val = None for m inrange(16): # 遍历第n-1层的dp第i列的最小值 if dp[n-1][m][i] < min_val_col: min_val_col = dp[n-1][m][i] row_of_min_val = m for j inrange(16): # 第n个表完全与第n-1个表有关, 可以与第n-2个表有关、但可以看作无关 dp[n][i][j] = min_val_col * step[n][i][j] prev[n][i][j] = row_of_min_val # pre记录了第n层[i][j]位置来自于第n-1层的哪一行,由于第n-1层的列决定了第n层的行,因此又可以通过i来确定第n-1层的列
min_val_ans = 100 min_i = None min_j = None for i inrange(16): for j inrange(16): if min_val_ans > dp[14][i][j]: min_val_ans = dp[14][i][j] min_i = i min_j = j
path = [(14, min_i, min_j)] for n inrange(14, 0, -1): i, j = path[-1][1], path[-1][2] m = prev[n][i][j] # m是第n层来自于第n-1层的那一行 path.append((n-1, m, i)) path.reverse()