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

Triangle

时间:2014-09-09 12:46:58      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:style   color   os   io   java   ar   strong   for   art   

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

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

Note:
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.

答案

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle)
    {
        if (triangle == null || triangle.size() == 0)
        {
            return 0;
        }
        final int ROW = triangle.size();
        int NUM = ROW * (ROW + 1) / 2;
        int minValue[] = new int[NUM];
        int position = 0;
        int row = 0, col;
        int rowStartIndex = 0;
        int result;
        minValue[position++ ] = triangle.get(0).get(0);
        for (row = 1; row < ROW; row++ )
        {
            rowStartIndex += row;
            List<Integer> rowList = triangle.get(row);
            minValue[position++ ] = rowList.get(0) + minValue[rowStartIndex - row ];
            int left=rowStartIndex-row;
            for (col = 1; col < row; col++ )
            {
                minValue[position++] = Math.min(minValue[left],
                    minValue[left+1])
                    + rowList.get(col);
                left++;
            }
            minValue[position++ ] = rowList.get(row ) + minValue[rowStartIndex - 1];
        }
        result = minValue[rowStartIndex];
        for (int i = 1; i < ROW; i++ )
        {
            result = Math.min(minValue[rowStartIndex + i], result);
        }
        return result;
    }
}


Triangle

标签:style   color   os   io   java   ar   strong   for   art   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39151839

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!