标签:
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
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.
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).
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 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5657094.html