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.
For example, given the following triangle
Example
[[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
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
n = len(triangle)
dp = [[0]*n for _ in range(n+1)]
dp[0][0] = triangle[0][0]
for i in range(1,n):
lenth = len(triangle[i])
for j in range(lenth):
if j==0:
dp[i][j]=dp[i-1][j]+triangle[i][j]
elif j==lenth-1:
dp[i][j]=dp[i-1][j-1]+triangle[i][j]
else:
dp[i][j]=min(dp[i-1][j-1]+triangle[i][j], dp[i-1][j]+triangle[i][j])
return min(dp[n-1][:n])