LeetCode 120. Triangle

来源:互联网 发布:多功能水枪 数据 编辑:程序博客网 时间:2024/05/27 00:30

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.

首先想到任意一点 p[i][j] 到底部的最小路径m[i][j]是由它后一排的相邻两个点到底的距离决定的

设数组p

因此得m[i][j] = p[i][j] + min(m[i+1][j] , m[i+1][j+1])
但是由于需要空间为o(n),n为行数
所以空间只存当前行后一行的min值,一次遍历覆盖一次
最终返回首元素就是答案

 public int minimumTotal(List<List<Integer>> triangle) {        int rows = triangle.size();        //获取最后一排        List<Integer> lastRow = triangle.get(rows - 1);        int[] tmp = new int[rows];        //初始化替换数组        for(int i = 0; i < rows; i++) {            tmp[i] = lastRow.get(i);        }        for (int i = rows - 2; i >= 0 ; i--) {            //获取当前行第i+1行,i+1个数            List<Integer> nowRow = triangle.get(i);            for (int j = 0; j < i + 1; j++) {                tmp[j] = nowRow.get(j) + Math.min(tmp[j], tmp[j + 1]);            }        }        return tmp[0];    }