Question
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
给出一个三角形,找出从其顶端到底端的最小路径的总和,每次移动是下一行的相邻数字。
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).
Solution
动态规划解。定义dp[i][j]:以triangle[i][j]结尾的最小路径。那么每个triangle[i][j]的上一层元素是相邻数字,我们只需把较小的路径保存下来即可。递推式:dp[i][j] = min(dp[i- 1][j] + triangle[i][j], dp[i - 1][j - 1] + triangle[i][j])。当然每一行的行首和行末元素的上一层都只有一个来源
class Solution(object): def minimumTotal(self, triangle): """ :type triangle: List[List[int]] :rtype: int """ if len(triangle) == 0: return 0 if len(triangle[0]) == 0: return 0 dp = [[float('inf') for _ in range(len(triangle[i]))] for i in range(len(triangle))] dp[0][0] = triangle[0][0] for index_r in range(1, len(triangle)): for index_c in range(len(triangle[index_r])): # 如果是当前行的最后一个元素,其上一层元素只能是dp[index_r - 1][index_c - 1] if index_c == len(triangle[index_r]) - 1: dp[index_r][index_c] = dp[index_r - 1][index_c - 1] + triangle[index_r][index_c] # 如果是当前和的第一个元素,其上一层元素只能是dp[index_r - 1][index_c] elif index_c == 0: dp[index_r][index_c] = dp[index_r - 1][index_c] + triangle[index_r][index_c] # 其余元素的上层元素均有两个 else: dp[index_r][index_c] = min(dp[index_r - 1][index_c] + triangle[index_r][index_c], dp[index_r - 1][index_c - 1] + triangle[index_r][index_c]) # 返回最后一行中最小的一个 return min(dp[-1])