题目描述:
题解:参考https://blog.csdn.net/qq_32424059/article/details/88075469
采用三角形自底向上的动态规划方法,在dp中保存结果,dp是和输入triangle结构相同的数组。
dp中每个位置代表从该位置到三角形最下层的最短距离,初始时dp最下面一层与triangle最下层相同。
动态规划:dp[i][j]=triangle[i][j]+min(dp[i+1][j],dp[i+1][j+1])
def minimumTotal(self, triangle): height = len(triangle) dp = [] for i in range(height): tmp = [] for j in range(len(triangle[i])): tmp.append(0) dp.append(tmp) dp[-1] = triangle[height-1] for i in range(height-2,-1,-1): for j in range(len(triangle[i])): dp[i][j] = triangle[i][j]+min(dp[i+1][j],dp[i+1][j+1]) return dp[0][0]