Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 120] Triangle

Question

link

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.

Stats

Frequency 1
Difficulty 3
Adjusted Difficulty 1
Time to use --------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This is a math question.

Solution

It’s an easy question. Instead of normal DP transition function, this one is so-called bottom-up approach.

Code

public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
    int len = triangle.size();
    if (len == 0) return 0;
    int[] m = new int[len];
    m[0] = triangle.get(0).get(0);
    for (int i = 1; i < len; i ++) {
        ArrayList<Integer> cur = triangle.get(i);
        for (int j = i; j >= 0; j --) {
            if (j == i) m[j] = m[j-1] + cur.get(j);
            else if (j == 0) m[j] = m[0] + cur.get(0);
            else m[j] = Math.min(m[j-1], m[j]) + cur.get(j);
        }
    }
    int min = Integer.MAX_VALUE;
    for (Integer k: m)
        min = Math.min(min, k);
    return min;
}