Triangle

来源:互联网 发布:根据域名添加路由设置 编辑:程序博客网 时间:2024/06/03 20:41

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.

思路 :  From  bottom to the top. Every time select the buffer[j] = Math.min(buffer[j], buffer[j + 1]) + cur.get(j);  At last return buffer[0];

易错点: 注意次序 和 SIZE

public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {        int len = triangle.size();        int[] buffer = new int[len];        List<Integer> bottom = triangle.get(len - 1);        for(int i = 0; i < len; i++){            buffer[i] = bottom.get(i);        }                for(int i = len - 2; i >= 0; i--){            List<Integer> cur = triangle.get(i);            for(int j = 0; j < cur.size(); j++){                buffer[j] = Math.min(buffer[j], buffer[j+1]) + cur.get(j);            }        }        return buffer[0];    }}


0 0