Leetcode 120. Triangle

Problem

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.

Algorithm

Dynamic Programming (DP). F(i, j) = min(F(i-1, j-1) + F(i-1, j)) + triangle(i, j).

Code

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

你可能感兴趣的:(Leetcode,leetcode,动态规划)