Leetcode 120. Triangle

动态规划,Python 3 实现:

源代码已上传 Github,持续更新。

"""
120. Triangle
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.
"""

class Solution:
    def minimumTotal(self, triangle):
        """
        :type triangle: List[List[int]]
        :rtype: int
        """

        # 增加行列各增加一行,便于边界处理
        height = len(triangle) + 1
        width = len(triangle[-1]) + 1
        optimal_matrix = [[0 for x in range(width)] for y in range(height)]

        width_range = width - 1
        for h in range(height - 2, -1, -1):
            for w in range(width_range):
                # 状态转移方程
                optimal_matrix[h][w] = min(optimal_matrix[h + 1][w], optimal_matrix[h + 1][w + 1]) + triangle[h][w]
            width_range -= 1

        return optimal_matrix[0][0]

if __name__ == '__main__':
    triangle = [
                 [2],
                [3,4],
               [6,5,7],
              [4,1,8,3]
            ]
    solution = Solution()
    print(solution.minimumTotal(triangle))

源代码已上传至 Github,持续更新中。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容