title :
Given a triangle, find the minimum path sum from top to bottom. Each step of the 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 11
is (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus Point If you be able to does this using only O(n) extra space, where n is the total Number of rows in the triangle.
code : OJ Test via runtime:82 ms
1 classSolution:2 #@param triangle, a list of lists of integers3 #@return An integer4 defminimumtotal (self, triangle):5 #Special Case6 ifLen (triangle) = =0:7 return08 #DP Visit9Level =len (triangle)TenDP = [0 forIinchrange (level)] One forIinchRange (level): A forJinchRange (len (triangle[i]) -1,-1,-1): - ifJ==len (Triangle[i])-1 : -DP[J] = dp[j-1] +Triangle[i][j] the elifj==0: -Dp[0] = dp[0] +Triangle[i][0] - Else: -Dp[j] = min (dp[j-1],dp[j]) +Triangle[i][j] + returnMIN (DP)
Ideas :
Typical dynamic programming, like the unique path, see details
Http://www.cnblogs.com/xbf9xbf/p/4250359.html
In addition, this problem has a bonus, how to use as little as possible extra space.
The general DP idea is to define an O (n) space, with additional space such as a triangle size.
This is only used for the size of the bottom layer of the triangle.
When traversing the layer I, the space storage of Dp[1:len (Triangle[i]) is used to store the minimum and the nodes to the first level of each node.
Note here: You can save the array space by traversing backwards. This is a common operation technique for array, see details
Http://www.cnblogs.com/xbf9xbf/p/4240257.html
Continuous brush problem, can be more related to the skills of the front and back, the ability to improve the code has a certain help.
Leetcode "Triangle" Python implementation