首页 > 其他 > 详细

Triangle

时间:2016-07-10 09:47:22      阅读:136      评论:0      收藏:0      [点我收藏+]

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).

 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 }

 

Triangle

原文:http://www.cnblogs.com/beiyeqingteng/p/5657094.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!