Simple readable solution in java


  • 0
    W
    public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int size =triangle.size();
        int [] res = new int [size];
        if(size==0) return 0;
        if(size==1) return triangle.get(0).get(0);
        for(int j=0; j<size;j++)
           res[j] = triangle.get(size-1).get(j);
    
        for(int i=size-2; i>=1;i--)
            for(int j=0; j<=i; j++)  //Error, should be j<=i here...
                res[j]=Math.min(res[j], res[j+1])+triangle.get(i).get(j);
            
         return Math.min(res[0], res[1])+triangle.get(0).get(0);
    }
    

    }


  • 3
    W

    Even simpler

    public int minimumTotal(List<List<Integer>> t) {
        int n = t.size();
        if(n == 0) return 0;
        int[] m = new int[n];
        
        for(int j = 0; j < t.get(n - 1).size(); j++)
            m[j] = t.get(n - 1).get(j);
            
        for(int i = n - 2; i >= 0; i--)
            for(int j = 0; j < t.get(i).size(); j++)
                m[j] = t.get(i).get(j) + Math.min(m[j], m[j + 1]);
        return m[0];
    }

  • 0
    L
     public int minimumTotal(List<List<Integer>> triangle) {
            int[] cur = new int[triangle.size()];
            //initial cur
            for(int i = 0; i < triangle.size(); i++) 
                cur[i] = triangle.get(triangle.size() - 1).get(i);
            
            for(int i = triangle.size() - 2; i >= 0; i--) {
                for(int j = 0; j <= i; j++) {
                   //update cur[] for each row, cur[i] is the minimum path value from bottom to node i;
                   if(cur[j] > cur[j+1]) {
                        cur[j] = cur[j+1] + triangle.get(i).get(j);
                   }else{
                        cur[j] += triangle.get(i).get(j);
                   }
                }
            }
            return cur[0];
        }
    

    same idea, our codes are almost the same!! any idea to improve it?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.