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

Triangle LeetCode |My solution

时间:2014-10-27 15:36:28      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   java   for   sp   

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

 

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        if (triangle == null) {
            return 0;
        }
        int rowNumber = triangle.size() ;
        int [][] minArray = new int [rowNumber][rowNumber];
        minArray[0][0] = triangle.get(0).get(0);
        
        for (int i = 1; i < rowNumber; i++) {
            for (int j = 0; j <= i ; j++) {
                if (j == 0)
                {
                    minArray[i][j] = minArray[i-1][j] + triangle.get(i).get(j) ;
                } else if (j == i  && j != 0)
                {
                    minArray[i][j] = minArray[i-1][j - 1] + triangle.get(i).get(j);
                } else {
                     minArray[i][j] = Math.min(minArray[i- 1][j] + triangle.get(i).get(j), minArray[i- 1][j - 1] + triangle.get(i).get(j));    
                }
            }
        }
        int min = minArray[rowNumber - 1][0];
        for (int i = 0; i < rowNumber; i++) {
            if (min > minArray[rowNumber - 1][i]) {
                min = minArray[rowNumber - 1][i];
            }
        }
        return min;

    }
}


 

Triangle LeetCode |My solution

标签:style   blog   io   color   os   ar   java   for   sp   

原文地址:http://blog.csdn.net/aresgod/article/details/40508219

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