"120-triangle (triangle)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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 one (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.
Main Topic
Given a triangle, find the smallest path from the top to the bottom, and each step can be moved from the previous row to the next row of adjacent numbers
Thinking of solving problems
Recursive equation:
F (0,0) =a[0][0]
F (i,0) =a[i][0]+f (i-1,0) (i>0)
F (i,i) =a[i][i]+f (i-1,i-1) (i>0)
F (i,j) =a[i][j]+min (f (i-1,j), F (i-1,j-1)) (0
Code Implementation
Algorithm implementation class
Import java.util.List; Public classSolution { Public int Minimumtotal(list<list<integer>> triangle) {if(Triangle = =NULL|| Triangle.size () <1) {return 0; }//Create the second dimension of the array int[] Minsum =New int[Triangle.size ()] [];//Create the first dimension of the array for(inti =0; i < minsum.length; i++) {Minsum[i] =New int[i +1]; }//Set the first lineminsum[0][0] = triangle.Get(0).Get(0);//Set other rows for(inti =1; i < minsum.length; i++) {list<integer> line = triangle.Get(i); for(intj =0; J < Minsum[i].length; J + +) {if(J = =0) {minsum[i][0] = line.Get(0) + Minsum[i-1][0]; }Else if(i = = j) {Minsum[i][j] = line.Get(j) + Minsum[i-1][j-1]; }Else if(J < i) {Minsum[i][j] = line.Get(j) + Math.min (Minsum[i-1][J], Minsum[i-1][j-1]); } } }//Find the minimum value of the last line is the solution intMin = minsum[minsum.length-1][0];intLength = Minsum[minsum.length-1].length; for(inti =1; i < length; i++) {if(Min > Minsum[length-1][i]) {min = minsum[length-1][i]; } }returnMin }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47651229"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "120-triangle (triangle)"