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.
思路
minpath[k][i] = min( minpath[k+1][i], minpath[k+1][i+1]) + triangle[k][i];
代码
Solution1: 直接递归(Time Limit Exceeded)
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
if len(triangle) == 1:
return triangle[0][0]
def helper(row, idx):
if row + 1 == len(triangle) - 1:
return triangle[row][idx] + min(triangle[row+1][idx], triangle[row+1][idx+1])
return triangle[row][idx] + min(helper(row+1, idx), helper(row+1, idx+1))
return helper(0, 0)
Solution2: 在以上基础上增加记忆数组
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
if len(triangle) == 1:
return triangle[0][0]
mem = [[None] * len(row) for row in triangle]
def helper(row, idx):
if row + 1 == len(triangle) - 1:
return triangle[row][idx] + min(triangle[row+1][idx], triangle[row+1][idx+1])
if mem[row+1][idx] != None:
left = mem[row+1][idx]
else:
left = helper(row+1, idx)
mem[row+1][idx] = left
if mem[row+1][idx+1] != None:
right = mem[row+1][idx+1]
else:
right = helper(row+1, idx+1)
mem[row+1][idx+1] = right
return triangle[row][idx] + min(left, right)
return helper(0, 0)
Solution3 (Best) : Bottom up; 循环; 只存一行数据,节省空间复杂度
改进为:
For the kth level:
minpath[i] = min( minpath[i], minpath[i+1]) + triangle[k][i];
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
if len(triangle) == 1:
return triangle[0][0]
line = triangle[-1].copy()
for i in range(len(triangle)-2, -1, -1):
for j in range(len(triangle[i])):
line[j] = triangle[i][j] + min(line[j], line[j + 1])
return line[0]