卖萌的弱渣

I am stupid, I am hungry.

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:

1
2
3
4
5
6
[
     [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).

Solution

  • DP: use triangle store the min
(Triangle.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
    """
    @param triangle: a list of lists of integers.
    @return: An integer, minimum path sum.
    """
    def minimumTotal(self, triangle):
        # write your code here
        # use triangle to store the min value
        # From bottom to top
        if triangle == None:
            return 0

        if len(triangle) == 1 and len(triangle[0]) == 1:
            return triangle[0][0]

        row = len(triangle)
        for i in range(row-2,-1,-1):
            for j in range(len(triangle[i])):
                triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1])
        return triangle[0][0]

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