[LeetCode]Triangle

来源:互联网 发布:sql创建存储过程 查询 编辑:程序博客网 时间:2024/05/20 11:24

题目描述

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.

给定一个三角形,求其最短路径和,其中你下一步只能移动到下一行的相邻位置。额外空间限制为O(n)。

解题思路


     通过题目的要求额外空间是O(n)我们可以分析得出,这O(n)的空间对应于最后一行每个数的路径和。
     观察三角形结构可以知道,sum[i,0]和sum[i,row(i).length- 1]分别只和sum[i-1,0]和sum[i-1,row(i - 1).length- 1]相关,而sum[i,j]则是sum[i-1,j-1]+value(i,j)和sum[i-1,j]+value(i,j)的最小值。因此我们只需用一个一维数组保存当前行的sum值,便可求得下一行的sum值。

需要注意的:
    在具体解题中,求sum数组时最好采用从后往前更新的方法,即先求sum[i,row(i ).length- 1]直到求出sum[i,0]。如果你采用先求sum[i,0]再循环求到sum[i,row(i ).length- 1]则需要添加额外的变量。因为这样循环,当前值会覆盖上一行的相应值。


代码


public static int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {int[] total = new int[triangle.size()];Arrays.fill(total, 0);for (int i = 0; i < triangle.size(); i++) {ArrayList<Integer> rowList = triangle.get(i);for (int j = rowList.size() - 1; j >= 0; j--) {if (j == 0 ) {total[j] += rowList.get(j);} else if (j == rowList.size() - 1) {total[j] = total[j-1] + rowList.get(j);} else {total[j] = Math.min(total[j-1] + rowList.get(j), total[j]+ rowList.get(j));}}}int min = total[0];for (int i = 1; i < total.length; i++) {if (total[i] < min)min = total[i];}return min;}


0 0