120. 三角形最小路徑和
問題:
給定一個三角形,找出自頂向下的最小路徑和。每一步只能移動到下一行中相鄰的結點上。
相鄰的結點 在這裏指的是 下標 與 上一層結點下標 相同或者等於 上一層結點下標 + 1 的兩個結點。
例如,給定三角形:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
自頂向下的最小路徑和爲 11(即,2 + 3 + 5 + 1 = 11)。
解決:
思想:
python代碼:
import copy
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
n=len(triangle)
dp=copy.deepcopy(triangle)
for i in range(n-2,-1,-1):
for j in range(len(dp[i])):
dp[i][j]=min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j]
return dp[0][0]