Triangle Leetcode Python

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).

这道题目采用动态规划,从最底下往上依次相加得到解。

this is a DP problem, we can solve this problem by suming up from the bottom to the top.

class Solution:
    # @param triangle, a list of lists of integers
    # @return an integer
    def minimumTotal(self, triangle):
        rownum=len(triangle)
        for index in reversed(range(rownum)):
            if index==rownum-1:
                m=triangle[index]
            else:
                for j in range(index+1):
                    m[j]=triangle[index][j]+min(m[j],m[j+1])
        return m[0]


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。