- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
#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
- Related Articles
- Sum of upper triangle and lower triangle in C++
- Valid Triangle Number in C++
- Pascal's Triangle in C++
- Biggest Reuleaux Triangle inscribed within a Square inscribed in an equilateral triangle in C?
- Maximum Perimeter Triangle from array in C++
- Find Perimeter of a triangle in C++
- Pascal's Triangle II in C++
- Minimum Sum Path in a Triangle in C++
- Maximum path sum in a triangle in C++
- If $AB = QR , BC = RP , CA = PQ$ , then(a) $ triangle ABC cong triangle PQR$(b) $ triangle CBA cong triangle PRQ$(c) $ triangle BAC cong triangle RPQ$
- Biggest Reuleaux Triangle within A Square in C?
- Print symmetric double triangle pattern in C language
- Sum triangle from an array in C programming
- Program to print Reverse Floyd’s triangle in C
- Maximum path sum in an Inverted triangle in C++

Advertisements