Triangle

Tags : array, dynamic-programming, leetcode, cpp, medium

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.

Examples #

Example 1:

Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The triangle looks like:
   2*
  3* 4
 6 5* 7
4 1* 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (* above).

Example 2:

Input: triangle = [[-10]]
Output: -10

Constraints #

Solutions #

1 #


class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        
        vector<vector<int>> dp(triangle.size());
        
        dp[0].push_back(triangle[0][0]);
        
        for(int i=1; i<dp.size(); i++){
            
            dp[i].resize(triangle[i].size());
            
            for(int j=0; j<(triangle[i].size()); j++){
                
                if( j==0 ) dp[i][j] = dp[i-1][j] + triangle[i][j];
                
                else if( j==triangle[i].size()-1 )
                    dp[i][j] = dp[i-1][j-1] + triangle[i][j];
                
                else{
                    if(dp[i-1][j-1]<dp[i-1][j])
                        dp[i][j] = dp[i-1][j-1] + triangle[i][j];
                    else
                        dp[i][j] = dp[i-1][j] + triangle[i][j];
                }
            }
        }
        return *min_element(dp[dp.size()-1].begin(),dp[dp.size()-1].end());
        
    }
};

2 #


class Solution {
public:
    int minimumTotal(vector<vector<int>>& arr) {
            int r,c, n = arr.size();
            
            for(r=n-2; r>=0; r--){
                for(c=0; c<=r; c++){
                    arr[r][c] += min(arr[r+1][c], arr[r+1][c+1]); 
                }
            }
    
            return arr[0][0];
        }
};