题目: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.
解题思路:
创建一个这个列表的拷贝用于记录从起点到达该点的最短路径,自上而下进行计算即可,最后一个列表中的最小值即所求答案
到达每一个点的最小值为该点的值加上一个点的值或上两个点中的最小值
代码:
class Solution: def minimumTotal(self, triangle): import copy mintri = copy.deepcopy(triangle) l = len(mintri) for i in range(1,l): for j in range(0,i+1): if j == 0: mintri[i][j] = mintri[i][j] + mintri[i-1][0] elif j == i: mintri[i][j] = mintri[i][j] + mintri[i-1][i-1] else: mintri[i][j] = mintri[i][j] + min(mintri[i-1][j-1], mintri[i-1][j]) return min(mintri[l-1])