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 is 11
(i.e., 2 + < Span style= "color:red" >3 + 5 + 1 = one).
Note:
Bonus Point If-able to does this using only O(n) extra space, where n is the total number of rows in the triangle.
"Java Code"
The key to public class solution {/* is reverse thinking. * According to test instructions will naturally want to find the best solution from top to bottom, but because the underlying element is more than the upper layer. * The calculation at the boundary is cumbersome. However, assuming bottom-up, the optimal solution of the current layer is calculated by layer, then the top is reached. is to find the optimal solution. */public int minimumtotal (list<list<integer>> triangle) {//Handle special cases first if (triangle = = null | | Triangle.size () = = 0) return 0; if (triangle.size () = = 1) return Triangle.get (0). Get (0); int n = triangle.size (); int[] below = new Int[n]; The optimal solution for preserving the next layer int[] cur = new Int[n]; The optimal solution for saving the current layer is int i, J; The initial value is the value of the following line list<integer> lastrow = Triangle.get (n-1); for (i = 0; i < n; i++) {Below[i] = Lastrow.get (i); }//start from the penultimate line to calculate the for (i = n-2; I >= 0; i--) {list<integer> row = triangle.g ET (i); The optimal solution for each position from the underlying to the current level depends on the two elements that are adjacent to the lower layer for (j = 0; J < Row.size (), j + +) {if (Below[j] < below[j + 1]) cur[j] = beLOW[J] + row.get (j); else Cur[j] = below[j + 1] + row.get (j); }//Level moves up, the current layer changes to lower for (j = 0; J < Row.size (), j + +) {Below[j] = Cur[j ]; }} return cur[0]; }}
Expand
In addition to the minimum output value addition, how to find this road?
"Leetcode" Triangle resolution Report