leetcode 120. 三角形最小路径和

动态规划
定义dp[i][j]为走到第i层,第j列的最短路径,每一层记录所有可能的最小值,然后去更新下一层,最后取底部的最小值即为最终答案
二维dp的写法

class Solution:
    def minimumTotal(self, triangle: List[List[int]]) -> int:
        n = len(triangle)
        dp = [[0] * n for _ in range(n)]
        dp[0][0] = triangle[0][0]
        for i in range(1, n):
            for j in range(i+1):
                if j == 0:
                    dp[i][j] = dp[i-1][0] + triangle[i][0]
                elif j == i:
                    dp[i][j] = dp[i-1][j-1] + triangle[i][j]
                else:
                    dp[i][j] = min(dp[i-1][j-1] + triangle[i][j], dp[i-1][j] + triangle[i][j])
        return min(dp[-1])

一维dp,内存优化。在进行每一层更新时,从右向左更新。如果还是从左往右这样顺序更新,因为是一维dp数组,那么后一个节点的路径值将会把同一层的前一个节点的值也计算进去,造成错误更新

class Solution:
    def minimumTotal(self, triangle: List[List[int]]) -> int:
        n = len(triangle)
        dp = [0] * n
        dp[0] = triangle[0][0]
        for i in range(1, n):
            for j in range(i, -1, -1): #同一层从后向前更新
                if j == i:
                    dp[j] = dp[j-1] + triangle[i][j]
                elif j == 0:
                    dp[j] = dp[j] + triangle[i][j]
                else:
                    dp[j] = min(dp[j-1] + triangle[i][j], dp[j] + triangle[i][j])
        return min(dp)

你可能感兴趣的:(leetcode 120. 三角形最小路径和)