Triangle in C++


Suppose we have a triangle. We have to find the minimum path sum from top to the bottom. In each step, we can move to adjacent numbers on the row below.

For example, if the following triangle is like

[
      [2],
     [3,4],
    [6,5,7],
   [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (2 + 3 + 5 + 1 = 11).

Let us see the steps −

  • Create one table to use in Dynamic programming approach.

  • n := size of triangle

  • for i := n – 2 down to 0

    • for j := 0 to i

      • dp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1]

  • return dp[0]

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int minimumTotal(vector<vector<int>>& triangle) {
      vector <int> dp(triangle.back());
      int n = triangle.size();
      for(int i = n - 2; i >= 0; i--){
         for(int j = 0; j <= i; j++){
            dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]);
         }
      }
      return dp[0];
   }
};
main(){
   Solution ob;
   vector<vector<int> > v = {{2},{3,4},{6,5,7},{4,1,8,3}};
   cout << ob.minimumTotal(v);
}

Input

[[2],[3,4],[6,5,7],[4,1,8,3]]

Output

11

Updated on: 28-Apr-2020

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements