Triangle
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-able to does this using only O(n) extra space, where n is the total number of rows in the triangle.
A typical DP problem. For a certain layer I, we just need to know the minimum path value at each number of the I-1 layer, and then select the small one corresponding to the first layer of the corresponding value, you can get the most recent minimum path value. Note that the least-left and right-most minimum-path values have only one source (two cannot be selected). Finally, all the shortest path values at the lowest level are obtained, and the smallest one can be selected.
For example, for the triangle in the example, the minimum path value at each location is:
[ 2], [5, 6], [one ,ten,], [18,16]]
In fact, it is not necessary to maintain the entire triangle (two-dimensional matrix), and only need to maintain two layers of data. For example, if you want to know the minimum path at the lowest level, you only need to know the minimum path of the second lowest. So you only need two arrays.
The code is as follows:
1 Public intMinimumtotal (list<list<integer>>triangle) {2 int[] DP =New int[Triangle.size ()];3 intRe = 0;4 for(intI=0;i<triangle.size (); i++) {5 int[] temp =New int[Triangle.size ()];6 for(intj=0;j<=i;j++) {7 if(j==0) {8TEMP[J] = dp[j]+Triangle.get (i). get (j);9Re =Temp[j];Ten } One Else if(j==i) ATEMP[J] = dp[j-1]+Triangle.get (i). get (j); - Else -TEMP[J] = Math.min (dp[j],dp[j-1]) +Triangle.get (i). get (j); theRe =Math.min (Re, temp[j]); - } -DP =temp; - } + - returnre; +}
[Leetcode] [JAVA] Triangled