This problem is very complicated.
If you consider the top-down direction, because the fork can only correct the two numbers below and right, the
final fork can only fall into a round partial fork, which may cause some hidden points to not be found .
For example:
1000
999 998
997 996 995
1 994 993 992
If you consider the global optimal, then consider the bottom-up dynamic programming method.
Without first considering the entire complex problem, we try to find the relationship of a local triangle.
For a triangle with only three elements
A
BC.
If DP (x, y) is defined as the minimum sum of (x, y) positions, enter the triangle two If the matrix is a,
we solve
it in the bottom-up direction, then DP (0,0) = min (DP (1,0), DP (1,1)) + a [0] [0]
because we can determine : The result of position [I] [J] is only related to the number below it and the number at the bottom right corner! !
class Solution:
def __init__(self):
self.tl = []
self.length = 0
self.tdict = {}
def minimumTotal(self, triangle: List[List[int]]) -> int:
self.tl = triangle
self.length = len(triangle)
if len(triangle) == 1:
return triangle[0][0]
else:
return self.dp(0,0)
def dp(self,x,y):
if x == self.length - 1:
return self.tl[-1][y]
elif str(x) + '_' + str(y) in self.tdict:
return self.tdict[str(x) + '_' + str(y)]
else:
res = min(self.dp(x+1,y),self.dp(x+1,y+1)) + self.tl[x][y]
self.tdict[str(x) + '_' + str(y)] = res
return res
Simplify the above code to get
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
length = len(triangle)
for i in range(length - 1,0,-1):
for j in range(i):
triangle[i-1][j] += min(triangle[i][j], triangle[i][j + 1])
return triangle[0][0]