序號 | 文獻 |
---|---|
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]