120. Triangle

来源:互联网 发布:数组结束标志 编辑:程序博客网 时间:2024/05/22 00:25

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



三角的含义 第一行一个数依次增加一个

所以最后一行元素的个数等于层高,因此建数组时维度是层高+1就可以实现不越界不溢出,每次处理的都是i 处理之后i在之后的计算中用不到了所以可以直接修改i的值


public class Solution {    public int minimumTotal(List<List<Integer>> trgl) {    int sz = trgl.size();    int[] results = new int[sz+1];        for(int i=sz-1; i>=0; i--) {        List<Integer> tmp = trgl.get(i);                for(int j=0; j<tmp.size(); j++) {            results[j] = Math.min(results[j], results[j+1]) + tmp.get(j);        }    }    return results[0];}}


或者从上到下 每层最左边的值只能有上一层最左边的值得到,最右边的值只能从上一层最右边的值得到

0 0