|
| 1 | +packagechapter4_DynamicProgrammingI; |
| 2 | + |
| 3 | +importutils.CommonUtils; |
| 4 | + |
| 5 | +/**Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. |
| 6 | +
|
| 7 | + Notice |
| 8 | +
|
| 9 | +Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. |
| 10 | +
|
| 11 | +Example |
| 12 | +Given the following triangle: |
| 13 | +
|
| 14 | +[ |
| 15 | + [2], |
| 16 | + [3,4], |
| 17 | + [6,5,7], |
| 18 | + [4,1,8,3] |
| 19 | +] |
| 20 | +The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). |
| 21 | +
|
| 22 | +*/ |
| 23 | +publicclassTriangle { |
| 24 | + |
| 25 | +/** |
| 26 | + * @param triangle: a list of lists of integers. |
| 27 | + * @return: An integer, minimum path sum. |
| 28 | + */ |
| 29 | +publicintminimumTotal(int[][]triangle) { |
| 30 | +if(triangle ==null ||triangle.length ==0)return0; |
| 31 | +intm =triangle.length,n =triangle[m-1].length;//you must use the last row's length which is the largest. But I'm using some unnecessary space here. |
| 32 | +int[][]paths =newint[m][n]; |
| 33 | +paths[0][0] =triangle[0][0]; |
| 34 | + |
| 35 | +//initialize column 0 since it's special in that it could get only descend from its upper one |
| 36 | +for(inti =1;i <m;i++){ |
| 37 | +paths[i][0] =paths[i-1][0] +triangle[i][0]; |
| 38 | + } |
| 39 | + |
| 40 | +CommonUtils.printMatrix(paths); |
| 41 | + |
| 42 | +intmin =Integer.MAX_VALUE; |
| 43 | + |
| 44 | +intcolMax =0; |
| 45 | +inti =1; |
| 46 | +for(;i <m;i++){ |
| 47 | +colMax =i; |
| 48 | +computeMinForThisRow(triangle,i,colMax,paths); |
| 49 | + } |
| 50 | + |
| 51 | +i--; |
| 52 | +for(intj =colMax;j >=0;j--){ |
| 53 | +min =Math.min(min,paths[i][j]); |
| 54 | + } |
| 55 | +CommonUtils.printMatrix(paths); |
| 56 | +returnmin; |
| 57 | + } |
| 58 | + |
| 59 | +voidcomputeMinForThisRow(int[][]triangle,introw,intcolMax,int[][]paths){ |
| 60 | +for(intj =1;j <=colMax;j++){//we start from column 1, since column 0 has been initialized already |
| 61 | +intleft =Integer.MAX_VALUE,right =Integer.MAX_VALUE; |
| 62 | +left =paths[row-1][j-1]; |
| 63 | +if(j <colMax)right =paths[row-1][j]; |
| 64 | +paths[row][j] =Math.min(left,right) +triangle[row][j]; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + |
| 69 | +publicstaticvoidmain(String...args){ |
| 70 | +Triangletest =newTriangle(); |
| 71 | +int[][]triangle =newint[][]{ |
| 72 | + {2}, |
| 73 | + {3,4}, |
| 74 | + {6,5,7}, |
| 75 | + {4,1,8,3} |
| 76 | + }; |
| 77 | +System.out.print(test.minimumTotal(triangle)); |
| 78 | + } |
| 79 | +} |