码迷,mamicode.com
首页 > 编程语言 > 详细

【LeetCode-面试算法经典-Java实现】【120-Triangle(三角形)】

时间:2017-05-23 19:42:18      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:line   递推   tom   href   function   title   var   not   sum   

【120-Triangle(三角形)】


【LeetCode-面试算法经典-Java实现】【全部题目文件夹索引】

原题

  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.

题目大意

  给定一个三角形,找出从顶究竟的最小路径和,每一步能够从上一行移动到下一行相邻的数字

解题思路

  递推方程:
  f(0,0)=a[0][0]
  f(i,0)=a[i][0]+f(i-1,0) (i>0)
  f(i,i)=a[i][i]+f(i-1,i-1)(i>0)
  f(i,j)=a[i][j]+MIN(f(i-1,j),f(i-1,j-1))(0

代码实现

算法实现类

import java.util.List;

public class Solution {

    public int minimumTotal(List<List<Integer>> triangle) {

        if (triangle == null || triangle.size() < 1) {
            return 0;
        }
        // 创建数组的第二维度
        int[][] minSum = new int[triangle.size()][];

        // 创建数组的第一维度
        for (int i = 0; i < minSum.length; i++) {
            minSum[i] = new int[i + 1];
        }
        // 设置第一行
        minSum[0][0] = triangle.get(0).get(0);
        // 设置其他行
        for (int i = 1; i < minSum.length; i++) {
            List<Integer> line = triangle.get(i);
            for (int j = 0; j < minSum[i].length; j++) {
                if (j == 0) {
                    minSum[i][0] = line.get(0) + minSum[i - 1][0];
                } else if (i == j) {
                    minSum[i][j] = line.get(j) + minSum[i - 1][j - 1];
                } else if (j < i) {
                    minSum[i][j] = line.get(j) + Math.min(minSum[i - 1][j], minSum[i - 1][j - 1]);
                }
            }
        }
        //找最后一行的最小值就是所求的解
        int min = minSum[minSum.length - 1][0];
        int length = minSum[minSum.length - 1].length;
        for (int i = 1; i < length; i++) {
            if (min > minSum[length - 1][i]) {
                min = minSum[length - 1][i];
            }
        }

        return min;
    }
}

评測结果

  点击图片。鼠标不释放。拖动一段位置。释放后在新的窗体中查看完整图片。

技术分享

特别说明

欢迎转载。转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47651229

【LeetCode-面试算法经典-Java实现】【120-Triangle(三角形)】

标签:line   递推   tom   href   function   title   var   not   sum   

原文地址:http://www.cnblogs.com/mfmdaoyou/p/6895566.html

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