120. Triangle 三角形最小路径和 code

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.

思路:

  1. 设置一个二维数组,最优值三角形 d p dp dp,并初始化数组元素为0。 d p [ i ] [ j ] dp[i][j] dp[i][j]代表 了从底向上递推时,走到三角形第i行第j列的最优解。
  2. 从三角形的底向上进行动态规划:
    a.动态规划边界条件:底上的最优值即为数字三角形的最后一层。
    b.利用 i i i 循环,从倒数第二层递推至第一层,对于每层的各列,进行动态规划递推:
    i i i行,第j列的最优解为 d p [ i ] [ j ] dp[i][j] dp[i][j],可到达 ( i , j ) (i,j) (i,j)的两个位置的最优解 d p [ i + 1 ] [ j ] dp[i+1][j] dp[i+1][j] d p [ i + 1 ] [ j + 1 ] dp[i+1][j+1] dp[i+1][j+1]:
    d p [ i ] [ j ] = m i n ( d p [ i + 1 ] [ j ] , d p [ i + 1 ] [ j + 1 ] ) + t r i a n g l e [ i ] [ j ] dp[i][j] = min(dp[i+1][j], dp[i+1][j+1]) + triangle[i][j] dp[i][j]=min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j]
  3. 返回 d p [ 0 ] [ 0 ] dp[0][0] dp[0][0].

d p [ i ] [ j ] = m i n ( d p [ i + 1 ] [ j ] , d p [ i + 1 ] [ j + 1 ] ) + t r i a n g l e [ i ] [ j ] dp[i][j] = min(dp[i+1][j], dp[i+1][j+1]) + triangle[i][j] dp[i][j]=min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j] 可以变成一维DP:

For the i-th level:
d p [ j ] = m i n ( d p [ j ] , d p [ j + 1 ] ) + t r i a n g l e [ i ] [ j ] dp[j] = min(dp[j], dp[j+1]) + triangle[i][j] dp[j]=min(dp[j],dp[j+1])+triangle[i][j]
同样可以写作:
$dp[j] = min(dp[j]+ triangle[i][j], dp[j+1]+ triangle[i][j]) $

# 时间复杂度为O(n^2),空间复杂度O(n)。n为三角形高度。
from typing import List
class Solution:
    def minimumTotal(self, triangle: List[List[int]]) -> int:
        """
        :type triangle: List[List[int]]
        :rtype: int
        """
        n = len(triangle)
        dp = triangle[-1]
        for i in range(n-2, -1, -1): # row 倒数第二行开始遍历
            for j in range(i + 1): 
                dp[j] = min(dp[j]+triangle[i][j], dp[j+1]+triangle[i][j]) 
        return dp[0]

triangle = [
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]
solution = Solution()
solution.minimumTotal(triangle)

你可能感兴趣的:(code)