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.
题解:
依然是动态规划题。
记录到每一层的每一个位置所需要的最小步数,层层遍历下去即可。其具体公式如下。
对于每一层,不为0和最后1个的那一步i和当前层level,其计算方式为。
step[level][i] = min( step[level-1][i-1] + triangle[level][i], step[level-1][i] + triangle[level][i])
当为第一个时,那么只有从上一层的0到达,最后一个时,同理。
当然题目说如果能用O(n)的空间是最好的。因此又使用了一个滚动数组。
具体做法是开2个数组。分别表示到达这一层和上一层的最小步数,代码如图。
step = [[999999 for i in range(len(triangle))], [999999 for i in range(len(triangle))]]
而状态判定也需要修改一下,改为使用index判断而不是level。index用level % 2来维护。index-1所对应的便是到达上一层的最小步数。
对于不是最后一个和不是第一个的元素i,修改如下
step[index][i] = min(step[index - 1][i - 1] + triangle[level][i], step[index - 1][i] + triangle[level][i])
代码如下
class Solution(object):
def minimumTotal(self, triangle):
if len(triangle) == 0:
return 0
if len(triangle) == 1:
return triangle[0][0]
step = [[999999 for i in range(len(triangle))], [999999 for i in range(len(triangle))]]
level = 1
step[0][0] = triangle[0][0]
while level < len(triangle):
index = level % 2
i = 0
while i < len(triangle[level]):
if i > 0 and i < len(triangle[level]) - 1:
step[index][i] = min(step[index - 1][i - 1] + triangle[level][i],
step[index - 1][i] + triangle[level][i])
# tmplist[i] = min(step[i] + triangle[level][i] , step[i-1] + triangle[level][i])
else:
if i == 0:
step[index][i] = step[index - 1][i] + triangle[level][i]
else:
step[index][i] = step[index - 1][i - 1] + triangle[level][i]
i = i + 1
level = level + 1
return min(step[index])