序号 | 文献 |
---|---|
1 | Leetcode-120-Triangle |
2 | [eetCode 120 - Triangle] |
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.python
For example, given the following trianglegit
[ [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).github
Note:this
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.spa
本题求解的是给到的一组三角形矩阵中,从上到下的路径中和最小的是多少。这里咱们反过来求解,自底向上,设dp[i]是从底部开始到顶部的第条路径的和。这里怎么理解呢?假如,三角形的底部有4个元素,那么从底部出发到达顶部的路径应该是有4条。所以dp[i]表明了第条路径的和。由于题目中的规则是在第i层的第j个数字,往下只能走i+1,j 或者i+1,j+1 2个数字。所以,dp[i] = 当前数字 + min(dp[i],dp[i+1])。到这里思路就很清晰了,咱们来看下实现。code
class Solution(object): def minimumTotal(self, triangle): """ :type triangle: List[List[int]] :rtype: int """ dp = [0] *( len(triangle) + 1 ) for i in range(len(triangle)-1,-1,-1): for j in range(0,i+1): dp[j] = triangle[i][j] + min(dp[j],dp[j+1]) print dp return dp[0]