LeetCode链接:https://leetcode-cn.com/problems/triangle/
思路:注意这里要计算每一条路径,也就是说只能穷举搜索所有的路径来找最优解,而不能通过类似 beam search 的方法降低复杂度。因为Beam Search不能保证是最优解。
空间复杂度为O(2n)
代码如下:
class Solution:
def minimumTotal(self, triangle):
if not len(triangle):
return 0
dp = [0] * len(triangle)
dp[0] = triangle[0][0]
dp_mid = dp.copy() # 深复制
for i in range(1, len(triangle)):
dp[i] = dp_mid[i - 1] + triangle[i][i]
dp[0] = dp_mid[0] + triangle[i][0]
for j in range(1, i):
dp[j] = min(dp_mid[j-1], dp_mid[j]) + triangle[i][j]
dp_mid = dp.copy() # 更新中间dp_mid数组
return min(dp)
可以自底向上将空间复杂度优化到O(n),代码如下,
def minimumTotal(triangle):
"""
1. dp问题: dp[i][j] = triangle[i][j] + min(dp[i+1][j], dp[i+1][j+1])
"""
mini, M = triangle[-1], len(triangle)
for i in range(M - 2, -1, -1):
for j in range(len(triangle[i])):
mini[j] = triangle[i][j] + min(mini[j], mini[j+1])
return mini[0]
print(minimumTotal([[2],[3,4],[6,5,7],[4,1,8,3]]))