Leetcode 120. triangle path and the minimum (Triangle)

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 D P [ i ] [ j ] DP[i][j] to reach the first ( i , j ) (i,j) minimum path node, the state transition is:
D P [ i ] [ j ] = m i n ( D P [ i 1 ] [ j 1 ] + t r i a n g l e [ i ] [ j ] , D P [ i 1 ] [ j ] + t r i a n g l e [ i ] [ j ] ) DP[i][j] = min(DP[i-1][j-1] + triangle[i][j], DP[i-1][j] + triangle[i][j])
If the direct use of the input data, then the formula will be D P DP are replaced t r i a n g l e triangle 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 O ( n ) O (n) additional space, i.e., open only a one-dimensional array, you can use the bottom-up method, first D P DP array initialization is t r i a n g l e triangle of the last line, then the following equation based on the state transition, the final result is D P [ 0 ] DP[0]
D P [ j ] = m i n ( D P [ j ] + t r i a n g l e [ i ] [ j ] , D P [ j + 1 ] + t r i a n g l e [ i ] [ j ] ) DP[j] = min(DP[j] + triangle[i][j], DP[j+1]+triangle[i][j])

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]
Published 32 original articles · won praise 53 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_39378221/article/details/104056290