首页 > 其他 > 详细

Leetcode 120. Triangle

时间:2021-04-08 15:27:20      阅读:4      评论:0      收藏:0      [点我收藏+]

Description: 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.

Link: 120. Triangle

Examples:

Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The triangle looks like:
   2
  3 4
 6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).

Example 2:
Input: triangle = [[-10]]
Output: -10

思路: 动态规划,求从顶到底的最短路径和。dp定义为从顶到该点的最短路径和。当前点可以来自上一层的i, i-1,但注意每行两边的更新。

class Solution(object):
    def minimumTotal(self, triangle):
        """
        :type triangle: List[List[int]]
        :rtype: int
        """
        n = len(triangle)
        if n == 0: return triangle[0][0]
        dp = [[0]*i for i in range(1,n+1)]
        # print(dp)
        dp[0][0] = triangle[0][0]
        for row in range(1, n):
            for i in range(row+1):
                if i == 0:
                    dp[row][i] = triangle[row][i] + dp[row-1][i]
                elif i > 0 and i < row:
                    dp[row][i] = triangle[row][i] + min(dp[row-1][i-1], dp[row-1][i])
                else:
                    dp[row][i] = triangle[row][i] + dp[row-1][i-1]
        return min(dp[-1])

之前看一篇讲解动态规划的,说的很对,动态规划就是防止重复计算,而把要重复的东西记录下来,方便最后答案的计算。所以找不到状态的时候,就想想什么东西要被重复记下来,可能是有用的。

日期: 2021-04-07 再不刷图,感觉毕业要失业

Leetcode 120. Triangle

原文:https://www.cnblogs.com/wangyuxia/p/14631895.html

(0)
(0)
   
举报
评论 一句话评论(0
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号