码迷,mamicode.com
首页 > 其他好文 > 详细

Triangle

时间:2016-07-10 09:48:42      阅读:125      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!