Leetcode 120. triangular minimum path and
1 title description ( Leetcode topic Link )
Given a triangle, find the minimum and the top-down path. Each step can move to the next line adjacent nodes. E.g:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
Top-down and minimum path 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note: If you can only use the extra space O (n) of (n is the number of rows in the triangle) to solve this problem, then your algorithm will be a plus.
2 solution to a problem
This entitled dynamic programming problem can be constructed using a matrix or a direct data input to the subject structure, defined
to reach the first
minimum path node, the state transition is:
If the direct use of the input data, then the formula will be
are replaced
can.
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
length = len(triangle)
for i in range(1,length):
for j in range(0,i+1):
if j == 0:
triangle[i][j] = triangle[i-1][j] + triangle[i][j]
continue
if j == i:
triangle[i][j] = triangle[i-1][j-1] + triangle[i][j]
continue
triangle[i][j] = min(triangle[i-1][j-1] + triangle[i][j], triangle[i-1][j] + triangle[i][j])
return min(triangle[length-1])
If you consider only
additional space, i.e., open only a one-dimensional array, you can use the bottom-up method, first
array initialization is
of the last line, then the following equation based on the state transition, the final result is
。
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
length = len(triangle)
DP = triangle[-1]
i = length - 2
while i >= 0:
for j in range(0, 1+i):
DP[j] = min(DP[j] + triangle[i][j], DP[j+1]+triangle[i][j])
i -= 1
return DP[0]