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.

Notice

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

Example

Given the following triangle:

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

Solution

坐标型动态规划,i, j坐标。

class Solution:
    """
    @param triangle: a list of lists of integers.
    @return: An integer, minimum path sum.
    """
    def minimumTotal(self, triangle):
        # write your code here
        n = len(triangle)
        F = [[0 for x in range(n)] for y in range(n)]
        F[0][0] = triangle[0][0]
        if triangle is None or n == 0:
            return -1
        if triangle[0] is None or n == 0:
            return -1
        for i in range(1,n):
            F[i][0] = F[i-1][0] + triangle[i][0]
            F[i][i] = F[i-1][i-1] + triangle[i][i]
        for i in range(1,n):
            for j in range(1,i):
                F[i][j] = min(F[i-1][j],F[i-1][j-1]) + triangle[i][j]
        return min(F[- 1])

Last updated

Was this helpful?