Wednesday, April 22, 2015

[LeetCode] Triangle

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).
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.
Solution: We target the bonus point. The only tricky part is to use temporary variables. 
public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int nRows = triangle.size();
        if (nRows == 0) return 0;
        int[] sum = new int[nRows];
        Arrays.fill(sum, 0);
        sum[0] = triangle.get(0).get(0);
        for (int i = 1; i < nRows; i++) {
            int tmp = sum[0];
            sum[0] += triangle.get(i).get(0);
            for (int j = 1; j < i; j++) {
                int tmp_tmp = sum[j];
                sum[j] = triangle.get(i).get(j) 
                       + Math.min(tmp, sum[j]);
                tmp = tmp_tmp;
            }
            sum[i] = triangle.get(i).get(i) + tmp;
        }
        Arrays.sort(sum);
        return sum[0];
    }
}

No comments:

Post a Comment