120. Triangle:
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).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
题目大意:
给出一三角堆,要求从堆顶沿着相邻的节点移动到堆底,每个节点有其对应的值,求一条路径使得所经过的所有节点的值的和最小(每层仅经过一个节点)
解题思路:
其实这题只要求出到达每一层的每一个节点的最短路径就可以了,而且每一层的节点的最短路径只与其上一层的节点路径有关,因此所需保存的信息就是上一层的节点信息,因此额外的空间为O(n),最终返回的结果为最后一层中的最小的数。代码如下:
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
pre = [i for i in range(len(triangle))]
pre[0] = triangle[0][0]
cur = pre[:]
for i in range(1,len(triangle)):
for j in range(len(triangle[i])):
if j - 1 >= 0 and j < len(triangle[i - 1]):
cur[j] = min(pre[j - 1],pre[j]) + triangle[i][j]
elif j - 1 >= 0:
cur[j] = pre[j - 1] + triangle[i][j]
else:
cur[j] = pre[j] + triangle[i][j]
pre = cur[:]
return min(cur)