Leetcode 120. Triangle (Python)
Related Topic
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.
For example, given the following triangle
Sample I/O
Example 1
[
[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.
Methodology
This question solved by Dynamic Programming. It is similar with question 64 64. Minimum Path Sum.
Find the base case:
The base case can be original 2D list, we will replace the value of each cell with minimum sum.
Find the pattern:
However, to use dynamic programming, we need to sum up each cell with it’s previous adjancent cell.
Answer:
When reach to the bottom row, then minimum number in the bottom row will be the answer.
Code
def minimumTotal(self, triangle: List[List[int]]) -> int:
m = len(triangle)
for i in range(1,m):
triangle[i][0]+=triangle[i-1][0]
triangle[i][-1]+=triangle[i-1][-1]
for i in range(2,m):
for j in range(1,i):
triangle[i][j]+=min(triangle[i-1][j-1], triangle[i-1][j])
print(triangle)
return min(triangle[-1])
BigO
Init the triangle will cost O(m-1). Then iterate all 2D dp array, it will cost O((m-2)*(m-4)). In total will cost (m-1+(m-2)*(m-4)) equal to (m^2-5m+7) so generally is O(n^2)