动态规划 python 实现 三角形最大值路径

# -*- coding: UTF-8 -*-

deep = 4
L = []
L.append([1])
L.append([2,3])
L.append([4,5,6])
L.append([7,8,9,10])

opt = []

opt_line = []

#递归动态规划
def search_the_best_answer(i,j):
    print(i,j)
    if i < deep:
        if opt[i][j] != -1:
            return opt[i][j]
        else:
            f1 = search_the_best_answer(i+1,j)
            f2 = search_the_best_answer(i+1,j+1)
            if f1>f2:
                f = f1 + L[i][j]
                opt[i][j] = f
            else:
                f = f2 + L[i][j]
                opt[i][j] = f
    else:
        f = 0
    return f


#递推动态规划
def search_the_best_answer_by_loop(i,j):
    #先把第一层铺设好,
    for index in range(0, deep):
        opt[deep - 1][index] = L[deep - 1][index]
    for x in range(deep -2,-1,-1):
        print("x:" + str(x))
        for y in range(0,x+1):
            print("y:" + str(y))
            opt[x][y] = max(opt[x+1][y],opt[x+1][y+1]) + L[x][y]
    print(opt[0][0])


#递推动态规划  空间优化
def search_the_best_answer_by_loop_low(i,j):
    #先把第一层铺设好,
    opt_line = [-1] * deep
    for index in range(0, deep):
        opt_line[index] = L[deep - 1][index]
    for x in range(deep -2,-1,-1):
        print("x:" + str(x))
        for y in range(0,x+1):
            print("y:" + str(y))
            opt_line[y] = max(opt_line[y],opt_line[y+1]) + L[x][y]
    print(opt_line[0])


# print(search_the_best_answer(0,0))

if __name__ == "__main__":
    for i in range(0,deep):  opt.append([-1] * deep)
    # print(search_the_best_answer(0, 0))
    # search_the_best_answer_by_loop(0,0)
    search_the_best_answer_by_loop_low(0,0)

你可能感兴趣的:(编程知识点概念)