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.
思路:
- 设置一个二维数组,最优值三角形 ,并初始化数组元素为0。 代表 了从底向上递推时,走到三角形第i行第j列的最优解。
- 从三角形的底向上进行动态规划:
a.动态规划边界条件:底上的最优值即为数字三角形的最后一层。
b.利用 循环,从倒数第二层递推至第一层,对于每层的各列,进行动态规划递推:
第 行,第j列的最优解为 ,可到达 的两个位置的最优解 、 :
- 返回 .
可以变成一维DP:
For the i-th level:
同样可以写作:
$dp[j] = min(dp[j]+ triangle[i][j], dp[j+1]+ triangle[i][j]) $
# 时间复杂度为O(n^2),空间复杂度O(n)。n为三角形高度。
from typing import List
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
"""
:type triangle: List[List[int]]
:rtype: int
"""
n = len(triangle)
dp = triangle[-1]
for i in range(n-2, -1, -1): # row 倒数第二行开始遍历
for j in range(i + 1):
dp[j] = min(dp[j]+triangle[i][j], dp[j+1]+triangle[i][j])
return dp[0]
triangle = [
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
solution = Solution()
solution.minimumTotal(triangle)