120. Triangle
- Total Accepted: 84503
- Total Submissions: 265352
- Difficulty: Medium
- Contributors: Admin
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).
Note:
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.
Code
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
if len(triangle) == 0:
return 0
if len(triangle) == 1:
return triangle[0][0]
last_level_sum = {0:triangle[0][0]}
for i in xrange(1, len(triangle)):
this_level_sum = {}
for j in xrange(len(triangle[i])):
if j == 0:
this_level_sum[j] = last_level_sum[0] + triangle[i][j]
elif j == len(triangle[i])-1:
this_level_sum[j] = last_level_sum[j-1] + triangle[i][j]
else:
this_level_sum[j] = min(last_level_sum[j], last_level_sum[j-1]) + triangle[i][j]
last_level_sum = this_level_sum
return min(last_level_sum.values())
Idea
You go from top to bottom. Record the minimum sum until every layer. If you use a bottom-up DP, the solution can be more elegant.
Reference:
https://discuss.leetcode.com/topic/1669/dp-solution-for-triangle/2