Header Ad

Leetcode Triangle problem solution

In this Leetcode Triangle problem solution, we have Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index I on the current row, you may move to either index i or index i + 1 on the next row.

Leetcode Triangle problem solution


Problem solution in Python.

def minimumTotal(self, triangle):
    m = len(triangle)
    n = len(triangle[-1])
    dp = [i for i in triangle[-1]]
    
    for i in range(m - 2, -1, -1):
        for j in range(len(triangle[i])):                
            dp[j] = min(dp[j], dp[j + 1]) + triangle[i][j]
        
    return dp[0]



Problem solution in Java.

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


Problem solution in C++.

class Solution {
public:

int minimumTotal(vector<vector<int>>& triangle) {
 int n=triangle.size();
 if(n==0) return 0;
 if(n==1) return triangle[0][0];
 int mine=INT_MAX;
 for(int i=1;i<n;i++)
 {
     for(int j=0;j<=i;j++)
     {
       if(j-1>=0&&j<=i-1)
          triangle[i][j]+=min(triangle[i-1][j],triangle[i-1][j-1]);
       else if(j>i-1&&j-1>=0)
           triangle[i][j]+=triangle[i-1][j-1];
       else if(j-1<0)
           triangle[i][j]+=triangle[i-1][j];
       
       if(i==n-1)
           mine=min(mine,triangle[i][j]);
     }
 }
    return mine;
}
};


Problem solution in C.

int minimumTotal(int** triangle, int triangleRowSize, int *triangleColSizes) {
    int i,j;
    if(triangleRowSize == 0) return 0;
    for(i=triangleRowSize-2;i>=0;i--){
        for(j=0;j<triangleColSizes[i];j++){
            if(triangle[i+1][j] < triangle[i+1][j+1]){
                triangle[i][j] += triangle[i+1][j];
            } else {
                triangle[i][j] += triangle[i+1][j+1];
            }
        }
    }
    return triangle[0][0];
}


Post a Comment

0 Comments