Triangle
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Notice
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.
Example
Given the following triangle:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Method 1: top to bottom
1 public class Solution { 2 /** 3 * @param triangle: a list of lists of integers. 4 * @return: An integer, minimum path sum. 5 */ 6 public int minimumTotal(int[][] triangle) { 7 if (triangle == null || triangle.length == 0 || triangle[0].length == 0) return 0; 8 9 for (int i = 1; i < triangle.length; i++) { 10 for (int j = 0; j <= i; j++) { 11 if (j == 0) { 12 triangle[i][j] += triangle[i - 1][j]; 13 } else if (j == i) { 14 triangle[i][j] += triangle[i - 1][j - 1]; 15 } else { 16 triangle[i][j] += Math.min(triangle[i - 1][j - 1], triangle[i - 1][j]); 17 } 18 } 19 } 20 int min = triangle[triangle.length - 1][0]; 21 for (int i = 1; i < triangle[triangle.length - 1].length; i++) { 22 min = Math.min(min, triangle[triangle.length - 1][i]); 23 } 24 return min; 25 } 26 }
Method 2: bottom to top
1 public class Solution { 2 3 public int minimumTotal(int[][] triangle) { 4 if (triangle == null || triangle.length == 0 || triangle[0].length == 0) return 0; 5 6 for (int i = triangle.length - 2; i >= 0; i--) { 7 for (int j = 0; j <= i; j++) { 8 triangle[i][j] += Math.min(triangle[i + 1][j], triangle[i + 1][j + 1]); 9 } 10 } 11 return triangle[0][0]; 12 } 13 }