Minimum Sum Path in a Triangle

Given a triangular structure of numbers, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

Examples :

Input : 
   2
  3 7
 8 5 6
6 1 9 3
Output : 11
Explanation : 2 + 3 + 5 + 1 = 11

Input :
   3
  6 4
 5 2 7
9 1 8 6
Output : 10
Explanation : 3 + 4 + 2 + 1 = 10



Naive Approach : Going through the Naive approach by traversing every possible path. But, this is costly. So, use Dynamic Programming here in order to reduce the time complexity.

There are two ways to reach the solution :
1. Memoization – Starting from the top node, traverse recursively with each node, till the pathsum of that node is calculated. And then store the result in an array. But this will take O(N^2) space to maintain the array.

2. Bottom up – Start from the nodes on the bottom row; the min pathsum for these nodes are the values of the nodes themselves. And after that, minimum pathsum at the ith node of kth row would be the minimum of the pathsum of its two children + the node’s value, i.e.:

memo[k][i] = min( memo[k+1][i], memo[k+1][i+1]) + A[k][i];

OR
Simply set memo as a 1D array, and update it
this will be space efficient also :

For the row k :

memo[i] = min( memo[i], memo[i+1]) + A[k][i];

Below is the implementation of above dynamic programming approach :

C++

// C++ program for Dynamic
// Programming implementation of
// Min Sum Path in a Triangle
#include <bits/stdc++.h>
using namespace std;
  
// Util function to find minimum sum for a path
int minSumPath(vector<vector<int> >& A)
{
    // For storing the result in a 1-D array,
    // and simultaneously updating the result.
    int memo[A.size()];
    int n = A.size() - 1;
  
    // For the bottom row
    for (int i = 0; i < A[n].size(); i++) 
        memo[i] = A[n][i];    
  
    // Calculation of the remaining rows,
    // in bottom up manner.
    for (int i = A.size() - 2; i >= 0; i--) 
        for (int j = 0; j < A[i + 1].size() - 1; j++) 
            memo[j] = A[i][j] + min(memo[j],
                                    memo[j + 1]);
  
    // return the top element
    return memo[0];
}
  
/* Driver program to test above functions */
int main()
{
    vector<vector<int> > A{ { 2 },
                            { 3, 9 },
                            { 1, 6, 7 } };
    cout << minSumPath(A);
    return 0;
}

Java

// Java program for Dynamic
// Programming implementation of
// Min Sum Path in a Triangle
import java.io.*;
import java.util.*;
  
class GFG
{
    static int A[][] = {{2}, 
                        {3, 9}, 
                        {1, 6, 7}};
                          
    // Util function to find 
    // minimum sum for a path
    static int minSumPath()
    {
        // For storing the result
        // in a 1-D array, and 
        // simultaneously updating 
        // the result.
        int []memo = new int[A.length];
        int n = A.length - 1;
      
        // For the bottom row
        for (int i = 0
                 i < A[n].length; i++) 
            memo[i] = A[n][i];
      
        // Calculation of the 
        // remaining rows, in
        // bottom up manner.
        for (int i = A.length - 2
                 i >= 0; i--) 
            for (int j = 0
                     j < A[i + 1].length - 1; j++) 
                memo[j] = A[i][j] + 
                          (int)Math.min(memo[j], 
                                   memo[j + 1]);
      
        // return the 
        // top element
        return memo[0];
    }
      
    // Driver Code
    public static void main(String args[])
    {
        System.out.print(minSumPath());
    }
}
  
// This code is contributed by 
// Manish Shaw (manishshaw1)

Python 3

# Python 3 program for Dynamic
# Programming implementation of
# Min Sum Path in a Triangle
  
# Util function to find 
# minimum sum for a path
def minSumPath(A):
      
    # For storing the result in 
    # a 1-D array, and simultaneously 
    # updating the result.
    memo = [None] * len(A)
    n = len(A) - 1
      
    # For the bottom row
    for i in range(len(A[n])): 
        memo[i] = A[n][i] 
  
    # Calculation of the
    # remaining rows,
    # in bottom up manner.
    for i in range(len(A) - 2, -1,-1): 
        for j in range( len(A[i + 1]) - 1): 
            memo[j] = A[i][j] + min(memo[j],
                                    memo[j + 1]);
  
    # return the top element
    return memo[0]
  
# Driver Code
A = [[ 2 ],
    [3, 9 ],
    [1, 6, 7 ]]
print(minSumPath(A))
  
# This code is contributed
# by ChitraNayal

C#

// C# program for Dynamic
// Programming implementation of
// Min Sum Path in a Triangle
using System;
using System.Collections.Generic;
using System.Linq;
  
class GFG {
      
    // Util function to find 
    // minimum sum for a path
    static int minSumPath(ref List<List<int>> A)
    {
          
        // For storing the result in a 1-D array,
        // and simultaneously updating the result.
        int []memo = new int[A.Count];
        int n = A.Count - 1;
      
        // For the bottom row
        for (int i = 0; i < A[n].Count; i++) 
            memo[i] = A[n][i]; 
      
        // Calculation of the remaining rows,
        // in bottom up manner.
        for (int i = A.Count - 2; i >= 0; i--) 
            for (int j = 0; j < A[i + 1].Count - 1; j++) 
                memo[j] = A[i][j] + 
                          (int)Math.Min(memo[j], 
                                   memo[j + 1]);
      
        // return the top element
        return memo[0];
    }
      
    // Driver Code
    public static void Main()
    {
        List<List<int>> A = new List<List<int>>();
        A.Add(new List<int> {2});
        A.Add(new List<int> {3, 9});
        A.Add(new List<int> {1, 6, 7});
        Console.WriteLine(minSumPath(ref A));
    }
}
  
// This code is contributed by 
// Manish Shaw (manishshaw1)

PHP

<?php
// PHP program for Dynamic
// Programming implementation of
// Min Sum Path in a Triangle
  
// Util function to find
// minimum sum for a path
function minSumPath(&$A)
{
    // For storing the result 
    // in a 1-D array, and
    // simultaneously updating 
    // the result.
    $memo = array();
    for ($i = 0; $i < count($A); $i++) 
        $memo[$i] = 0;
  
    $n = count($A) - 1;
  
    // For the bottom row
    for ($i = 0; 
         $i < count($A[$n]); $i++) 
        $memo[$i] = $A[$n][$i]; 
  
    // Calculation of 
    // the remaining rows,
    // in bottom up manner.
    for ($i = count($A) - 2; $i >= 0; $i--) 
        for ($j = 0; 
             $j < count($A[$i + 1]) - 1; $j++) 
            $memo[$j] = $A[$i][$j] + 
                        min($memo[$j],
                        $memo[$j + 1]);
  
    // return the 
    // top element
    return $memo[0];
}
  
// Driver Code
$A = array(array(2),
           array(3, 9),
           array(1, 6, 7));
echo (minSumPath($A)); 
  
// This code is contributed 
// by Manish Shaw(manishshaw1)
?>

Output:

6


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Improved By : manishshaw1, ChitraNayal




Practice Tags :

Recommended Posts:



2.3 Average Difficulty : 2.3/5.0
Based on 12 vote(s)






User Actions