Triangle Leetcode Python

来源:互联网 发布:oracle连接mysql详解 编辑:程序博客网 时间:2024/06/05 02:50
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]


0 0
原创粉丝点击