# LeetCode 120. 三角形最小路径和

·  阅读 625

## 题目地址(120. 三角形最小路径和)

leetcode-cn.com/problems/tr…

## 题目描述

示例 1：

2
3 4
6 5 7
4 1 8 3



1 <= triangle.length <= 200 triangle[0].length == 1 triangle[i].length == triangle[i - 1].length + 1 -104 <= triangle[i][j] <= 104

## 思路

DP规划，把每一组状态存储在DP数组里面，优化空间方法是把【-2】数组的去掉，只保存【-1】和现在遍历的数组进行约简

## 代码

• 语言支持：Python3

Python3 Code:


class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
cengNum = len(triangle)
dp = []
for i in range(cengNum):
dp.append([0]*len(triangle[i]))
dp[0][0] = triangle[0][0]
for i in range(1,cengNum):
cengList = triangle[i]
for j,val in enumerate(cengList):
## 三角形边
if j == 0:
dp[i][j] = dp[i-1][j]+val
elif j == len(cengList)-1:
dp[i][j] = dp[i-1][j-1]+val
else:#中心位置采用min算
dp[i][j] = min(dp[i-1][j-1],dp[i-1][j])+val
res = min(dp[-1])
# print(dp)
return res

if __name__ == '__main__':
triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
# triangle = [[-10]]
res = Solution().minimumTotal(triangle)
print(res)



• 时间复杂度：$O(n^2)$
• 空间复杂度：$O(n^2)$