Search This Blog

Friday, December 28, 2012

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.
public class Solution {
    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(triangle==null || triangle.size()==0) return 0;
        ArrayList<Integer> res = new ArrayList<Integer>();
        for(int i=0;i<triangle.size();i++){
            ArrayList<Integer> temp = triangle.get(i);
            res.add(0,i>0?temp.get(0)+res.get(0):temp.get(0));
            for(int j=1;j<res.size()-1;j++){
                res.set(j,Math.min(res.get(j),res.get(j+1))+temp.get(j));
            }
            if(res.size()>1)
                res.set(res.size()-1,res.get(res.size()-1)+temp.get(res.size()-1));
        }
        
        int min=Integer.MAX_VALUE;
        for(Integer temp:res){
            min=Math.min(temp,min);
        }
        return min;
    }
}

No comments: