DP

LeetCode 120 Triangle (Python)

Posted by 小明MaxMing on April 24, 2021

题目

Given a triangle array, return the minimum path sum from top to bottom.

For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.

解题思路

dp[i][j] = min(dp[i + 1][j], dp[i + 1][j + 1]) + triangle[i][j]

dp[0][0]为所求

代码

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

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅