"120-triangle (triangle)""leetcode-Interview algorithm classic-java Implementation" "All Topics folder 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, and each step can move from the previous row to the next row of numbers adjacent
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 }}
Assessment Results
Click on the picture. The mouse is not released. Drag a section of the position. After release, view the full picture in the new form.
Special InstructionsWelcome reprint. Reprint Please specify the source "http://blog.csdn.net/derrantcm/article/details/47651229"
"Leetcode-Interview algorithm classic-java Implementation" "120-triangle (triangle)"