|
| 1 | +package chapter4_DynamicProgrammingI; |
| 2 | + |
| 3 | +import utils.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 | +public class Triangle { |
| 24 | + |
| 25 | + /** |
| 26 | + * @param triangle: a list of lists of integers. |
| 27 | + * @return: An integer, minimum path sum. |
| 28 | + */ |
| 29 | + public int minimumTotal(int[][] triangle) { |
| 30 | + if(triangle == null || triangle.length == 0) return 0; |
| 31 | + int m = 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 = new int[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(int i = 1; i < m; i++){ |
| 37 | + paths[i][0] = paths[i-1][0] + triangle[i][0]; |
| 38 | + } |
| 39 | + |
| 40 | + CommonUtils.printMatrix(paths); |
| 41 | + |
| 42 | + int min = Integer.MAX_VALUE; |
| 43 | + |
| 44 | + int colMax = 0; |
| 45 | + int i = 1; |
| 46 | + for(; i < m; i++){ |
| 47 | + colMax = i; |
| 48 | + computeMinForThisRow(triangle, i, colMax, paths); |
| 49 | + } |
| 50 | + |
| 51 | + i--; |
| 52 | + for(int j = colMax; j >= 0; j--){ |
| 53 | + min = Math.min(min, paths[i][j]); |
| 54 | + } |
| 55 | + CommonUtils.printMatrix(paths); |
| 56 | + return min; |
| 57 | + } |
| 58 | + |
| 59 | + void computeMinForThisRow(int[][] triangle, int row, int colMax, int[][] paths){ |
| 60 | + for(int j = 1; j <= colMax; j++){//we start from column 1, since column 0 has been initialized already |
| 61 | + int left = 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 | + public static void main(String...args){ |
| 70 | + Triangle test = new Triangle(); |
| 71 | + int[][] triangle = new int[][]{ |
| 72 | + {2}, |
| 73 | + {3,4}, |
| 74 | + {6,5,7}, |
| 75 | + {4,1,8,3} |
| 76 | + }; |
| 77 | + System.out.print(test.minimumTotal(triangle)); |
| 78 | + } |
| 79 | +} |
0 commit comments