Friday, March 20, 2015

120. Triangle Leetcode Java

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:
Let's look at the bottom row of the triangle, 4,1,8,3, which are 4 outlets for the Path sum, The minimum Path must end in one of this element. Let's assume the minimum Path pass the tri[2][0]: 6, so when the path goes to last row, it has to choose 1 as the exist rather than 4, so we can eliminate 4 for tri[2][0]. So we can say if the minimum path tri[2][0], it must also pass tri[3][1], similarly, if the path pass tri[2][1]:5, it must pass tri[3][1]:1 as well; tri[2][2]:7 -> tri[3][3]. So basically, if we can eliminate the last row, by setting the tri[2] as 6+1=7, 5+1=6 , 7+3=10.  For tri[1] can be done at the same manner: 6+3=9; 4+6=10 and tri[0] will be 9+2=11
Time complexity:O(m*n); Extra space : O(n)
  public int minimumTotal(List<List<Integer>> triangle) {  
     List<Integer> res=new ArrayList<Integer>(triangle.get(triangle.size()-1));  
     for(int i=triangle.size()-1;i>=1;i--){  
       for(int j=0; j<i;j++){  
         res.set(j,Math.min(res.get(j),res.get(j+1))+triangle.get(i-1).get(j));  
       }  
     }  
     return res.get(0);  
   }  

No comments:

Post a Comment