109. Triangle/120. Triangle
- 本题难度: Medium
- Topic: Dynamic Programming
Description
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Example
example 1
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).
example 2
Given the following triangle:
[
[2],
[3,2],
[6,5,7],
[4,4,8,1]]
The minimum path sum from top to bottom is 12 (i.e., 2 + 2 + 7 + 1 = 12).
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.
我的代码
class Solution:
"""
@param triangle: a list of lists of integers
@return: An integer, minimum path sum
"""
def minimumTotal(self, triangle):
# write your code here
l = len(triangle)
if l == 0:
return 0
if l == 1:
return triangle[0][0]
res = triangle[-1]
for i in range(l-2,0,-1):
for j in range(len(triangle[i])):
res[j] = triangle[i][j]+min(res[j],res[j+1])
return triangle[0][0]+min(res[:2])
思路
从下往上,每一个都是到达下面相邻的两个元素中路径中较小的加上当前元素之和,作为到达该位置的最小路径
[2], ^ [2]
[3, 4], | [9, 10, 10, 3]
[6, 5, 7], | [7, 6, 10, 3]
[4, 1, 8, 3] | [4, 1, 8, 3]
注意特殊情况:
只有一个元素和空三角形
- 时间复杂度 O(n^2)
- 空间复杂度 O(n)