120. Trangle

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, calculate from bottom to top

dp[i][j] = Math.min(dp[i+1][j], dp[i+1][j+1])+currentValue;
class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        // calculate from bottom to top
        // let i be the i-th layer (count from top to bottom)
        // let j be the j-th element of i-th layer (from left to right);
        // dp[i][j] = Math.min(dp[i+1][j], dp[i+1][j+1]);
        int layers = triangle.size();
        for (int i = layers-2; i>=0; i--){
            int size = triangle.get(i).size();
            for (int j=0; j<size;j++){
                int curr = triangle.get(i).get(j);
                int left = triangle.get(i+1).get(j);
                int right = triangle.get(i+1).get(j+1);
                triangle.get(i).set(j, Math.min(left, right)+curr);
            }
        }
        
        return triangle.get(0).get(0);
    }
}

Last updated