classSolution: defminimumTotal(self, triangle): """ :type triangle: List[List[int]] :rtype: int """ length = len(triangle) dp = triangle[-1] for i in range(length-2, -1, -1): # 从倒数第二行开始,一直到第一行 for j in range(i+1): # 在每一行计算时,从前到后 dp[j] = triangle[i][j] + min(dp[j], dp[j+1]) return dp[0]
Go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcminimumTotal(triangle [][]int)int { var min int length := len(triangle) dp := triangle[length-1] for i := length-2; i > -1; i-- { for j := 0; j < i+1; j++ { min = dp[j] if dp[j+1] < min { min = dp[j+1] } dp[j] = triangle[i][j] + min } } return dp[0] }