1 topics
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.
2 Ideas
This is a dynamic planning problem, the number of data per row corresponds to the number of rows, set F[m,n] to reach the first row m, nth column of the minimum cost, then there are
F[m,n]=min{f[i-1,j]+b,f[i-1,j-1]+b}, where B is the M row, the number of the nth column
So what about the boundary value?
I am setting the normal value starting from 1, 0 and the last one of the values is Intmax.
I think of this problem by myself.
3 Code
① space O (n^2), first thought of this
Public intMinimumtotal (list<list<integer>>triangle) { intLineNumber =triangle.size (); Integer[][] F=NewInteger[linenumber][linenumber+2]; //F (A, B) = Min{f (a-1,b-1) +b,f (a-1,b) +b} f (A, A, b) indicates the minimum cost of the second line of section a//set F (a,0) to Max, F (A, B) to Max, where B = Triangle.get (a). Size () +1, 0<=a<linenumber; //set the initial valuef[0][1] = triangle.get (0). Get (0); for(inti = 0; i < linenumber; i++) {f[i][0] =Integer.max_value; intLinesize = Triangle.get (i). Size () + 1; F[i][linesize]=Integer.max_value; }//long former = 0; //Dynamic Programming for(inti = 1; i < linenumber; i++) {List<Integer> row =Triangle.get (i); intRowsize =row.size (); for(intj = 1; J <= Rowsize; J + +) {F[i][j]= Math.min (F[i-1][j-1], f[i-1][j]) + row.get (j-1); } } intMin = f[linenumber-1][1]; for(inti = 1; I <= linenumber; i++) { inttemp = F[linenumber-1][i]; if(Temp <min) {min=temp; } } returnmin; }
② space O (n), improved a bit
Public intMinimumTotal2 (list<list<integer>>triangle) { intLineNumber =triangle.size (); Integer[][] F=NewInteger[2][linenumber+2]; //F (A, B) = Min{f (A-1,b-1), F (a-1,b)} + B; F (A, B) represent the minValue of the A row B list//set the initial value and the boundary valueF[0][0] =Integer.max_value; f[0][1] = triangle.get (0). Get (0); f[0][2] =Integer.max_value; //Dynamic Programming for(inti = 1; i < linenumber; i++) {List<Integer> row =Triangle.get (i); intRowsize =row.size (); for(intj = 1; J <= Rowsize; J + +) {f[1][J] = Math.min (F[0][j-1], f[0][j]) + row.get (j-1); } f[1][0] =Integer.max_value; f[1][ROWSIZE+1] =Integer.max_value; for(intj = 0; J <= Rowsize+1; J + +) {f[0][J] = f[1][j]; } } intmin = f[linenumber > 1? 1:0][1]; for(inti = 1; I <= linenumber; i++) { inttemp = f[linenumber > 1? 1:0][i]; if(Temp <min) {min=temp; } } returnmin; }
[Leetcode 120]triangle space O (n) algorithm