|
| 1 | +""" |
| 2 | +Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. |
| 3 | + |
| 4 | +For example, given the following triangle |
| 5 | + |
| 6 | +[ |
| 7 | + [2], |
| 8 | + [3,4], |
| 9 | + [6,5,7], |
| 10 | + [4,1,8,3] |
| 11 | +] |
| 12 | +The minimum path sum from top to bottom is 11 (i.e., 2 +たす 3 +たす 5 +たす 1 =わ 11). |
| 13 | + |
| 14 | +Note: |
| 15 | + |
| 16 | +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. |
| 17 | + |
| 18 | +从底到顶,min(self+right)。 |
| 19 | + |
| 20 | +O(1) 空间。 |
| 21 | + |
| 22 | +beat |
| 23 | +99% |
| 24 | + |
| 25 | +测试地址: |
| 26 | +https://leetcode.com/problems/triangle/description/ |
| 27 | + |
| 28 | + |
| 29 | + |
| 30 | +""" |
| 31 | +class Solution(object): |
| 32 | + def minimumTotal(self, triangle): |
| 33 | + """ |
| 34 | + :type triangle: List[List[int]] |
| 35 | + :rtype: int |
| 36 | + """ |
| 37 | + |
| 38 | + for i in range(len(triangle)-2, -1, -1): |
| 39 | + length = len(triangle[i]) |
| 40 | + for j in range(length): |
| 41 | + |
| 42 | + _right = triangle[i+1][j+1] |
| 43 | + _self = triangle[i+1][j] |
| 44 | + mins = min(_right, _self) |
| 45 | + triangle[i][j] += mins |
| 46 | + return min(triangle[0]) |
0 commit comments