Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
分析:
最短路径,一般是动态规划。
有两种方法。一种自顶向下,一种自底向上。但是,自顶向下,想来比较复杂,而自底向上,就比较简单了。用一个数组去保存当前行的最小值,依次向上。具体思路见代码。
code:
def minipath(triangle):
n = len(triangle)+1 # ➕1是为了构造一行元素都为0的行
ans = [0]*n # 就是这行
for i in range(n-2, -1, -1):
for j in range(i+1):
ans[j] = min(ans[j], ans[j+1]) + triangle[i][j]
return ans[0]