Saturday, January 10, 2015

LeetCode 120: 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.
public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        // From top to bottom to calculate the sum --- O(1) extra space
        int n = triangle.size();
        
        if (n == 0)
            return 0;
        
        if (n == 1)
            return triangle.get(0).get(0);
            
        for (int i = 1; i < n; i++)
        {
            List<Integer> above = triangle.get(i-1);
            List<Integer> row = triangle.get(i);
            
            for (int j = 0; j <= i; j++)
            {
                if (j == 0)
                    row.set(j, row.get(j) + above.get(j));
                else if (j == i)
                    row.set(j, row.get(j) + above.get(j-1));
                else
                    row.set(j, row.get(j) + Math.min(above.get(j-1), above.get(j)));
            }
        }
        
        int min = Integer.MAX_VALUE;
        
        for (int num : triangle.get(n-1))
            min = Math.min(min, num);
        
        return min;
    }
}

No comments:

Post a Comment