120. Triangle
120. Triangle
0. 参考文献
序号 | 文献 |
---|---|
1 | Leetcode-120-Triangle |
2 | [eetCode 120 - Triangle] |
1.题目
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.
2. 思路
本题求解的是给到的一组三角形矩阵中,从上到下的路径中和最小的是多少。这里我们反过来求解,自底向上,设dp[i]是从底部开始到顶部的第条路径的和。这里怎么理解呢?假如,三角形的底部有4个元素,那么从底部出发到达顶部的路径应该是有4条。因此dp[i]代表了第条路径的和。因为题目中的规则是在第i层的第j个数字,往下只能走i+1,j 或者i+1,j+1 2个数字。因此,dp[i] = 当前数字 + min(dp[i],dp[i+1])。到这里思路就很清晰了,我们来看下实现。
3. 实现
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]
编程光~