[120] Leetcode triangular minimum path and

Leetcode 120. triangular minimum path and

Title Description

Given a triangle, find the minimum and the top-down path. Each step can move to the next line adjacent nodes.

For example, given triangle:

[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
top-down and minimum path 11 (i.e., 2 + 3 + 5 + 1 = 11).

Description:

If you can use only O (n) extra space (n number of rows as a triangle) to solve this problem, then your algorithm will be a plus.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/triangle

Thinking

Dp variables to store the site. M is the number of layers is provided, i from 0 to m-1, j is an element index of each layer.
The following three cases:
when j = 0 when:
Triangle [I] [J] = Triangle [. 1-I] [J] Triangle + [I] [J]
when j = len (triangle [i] ) - 1 when :
Triangle [I] [J] = Triangle [I] [J] Triangle + [. 1-I] [J. 1-]
other cases:
Triangle [I] [J] = min (Triangle [. 1-I] [J- 1], triangle [i-1 ] [j]) + triangle [i] [j]

Code

class Solution:
    def minimumTotal(self, triangle: List[List[int]]) -> int:
        if triangle == [[]]:
            return 0
        if len(triangle)==1:
            return triangle[0][0]
        m = len(triangle)
        for i in range(1,m):
            for j in range(len(triangle[i])):
                if(j==0):
                    triangle[i][j] = triangle[i-1][j] + triangle[i][j]
                elif(j==len(triangle[i])-1):
                    triangle[i][j] = triangle[i][j] + triangle[i-1][j-1]
                else:
                    triangle[i][j] = min(triangle[i-1][j-1],triangle[i-1][j]) + triangle[i][j]
        return min(triangle[m-1])
Published 97 original articles · won praise 55 · views 130 000 +

Guess you like

Origin blog.csdn.net/voidfaceless/article/details/104108718