leetcode

Triangle

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

Use bottom up idea to calculate what is the min sum for current element plus current element's next level elements.

e.g: row 3, column 1 6+min(4,1) = 7

public int minimumTotal(List<List<Integer>> triangle) {
        int[] results = new int[triangle.size()];
        List<Integer> lastRow = triangle.get(results.length-1);      

        //set results to lastRow value
        for (int i=0; i<lastRow.size(); i++) {
            results[i] = lastRow.get(i);
        }

        //calculate from bottom up, the second to last row
        for (int i=triangle.size()-2; i>=0; i--) {
            List<Integer> currentRow = triangle.get(i);
            for (int j=0; j<currentRow.size(); j++) {
                //current row value + small value from row below (j, j+1);
                results[j] = currentRow.get(j) + Math.min(results[j], results[j+1]);
            }
        }

        return results[0];
    }