lc120. Triangle

110 阅读1分钟
  1. Triangle Medium

1963

236

Add to List

Share 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.

Accepted

思路:动态规划

1.问题拆解: 经过[i][j]的路径肯定会经过[i-1][j]或者[i-1][j-1]

2.状态定义: 从上到下,从下到上,从下到上,状态定义变为最后一行元素到当前元素最小路径和

3.递推方程推导

倒推 dp[i][j]=min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j]

4.实现

代码:python3

class Solution:
    def minimumTotal(self, triangle: List[List[int]]) -> int:
        for i in range(len(triangle)-2,-1,-1):
            for j in range(len(triangle[i])):
                triangle[i][j]=triangle[i][j]+min(triangle[i+1][j],triangle[i+1][j+1])
        return triangle[0][0]

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

参考:mp.weixin.qq.com/s?__biz=MzU…

时间复杂度:O(n^2)

空间复杂度:O(1)