120. Triangle - jiejackyzhang/leetcode-note GitHub Wiki

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

解题思路为Dynamic Programming。

可以采用down-top的方式,因为计算i-th row的时候,会用到i+1-th row的数据。 可以设一个数组A,长度为bottom row的长度,A[j]为由底部走到这一行第j个元素时的最小sum。 若i-th row的第j个数字在path中,可由i+1-th row的第j,j+1个数字而来,A[j] = min(A[j], A[j+1])+triangle[i][j]。 由此可以看到,数组A对于每一行可以重复利用,因此空间复杂度为O(n)。 最后的A[0]即为由底部走到顶端的minimum path sum。

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int[] A = new int[triangle.size()+1];
        for(int i = triangle.size()-1; i >= 0; i--){
            for(int j = 0; j < triangle.get(i).size(); j++){
                A[j] = Math.min(A[j], A[j+1]) + triangle.get(i).get(j);
            }
        }
        return A[0];
    }
}
⚠️ **GitHub.com Fallback** ⚠️