Skip to content

Commit 16230cd

Browse files
Merge pull request #597 from thisabhijeet/minFallingPathSumTriangle
minFallingPathSumTriangle.cpp created
2 parents c003db5 + 4bcce70 commit 16230cd

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// Problem : Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an
2+
// adjacent number of the row below.More formally, if you are on index i on the current row, you may move to either
3+
// index i or index i + 1 on the next row.
4+
5+
#include <bits/stdc++.h>
6+
using namespace std;
7+
8+
int minimumTotal(vector<vector<int>> &triangle)
9+
{
10+
int n = triangle.size();
11+
vector<vector<int>> dp(n);
12+
for (int i = 0; i < n; i++)
13+
{
14+
for (int j = 0; j < triangle[i].size(); j++)
15+
{
16+
if (i == 0 and j == 0)
17+
{
18+
// very first cell
19+
dp[i].push_back(triangle[i][j]);
20+
}
21+
else if (j == 0)
22+
{
23+
// we can jump to this cell by one way(⬇️)
24+
dp[i].push_back(dp[i - 1][j] + triangle[i][j]);
25+
}
26+
else if (j == (triangle[i].size() - 1))
27+
{
28+
// we can jump to this cell by one way(↘️)
29+
dp[i].push_back(dp[i - 1][j - 1] + triangle[i][j]);
30+
}
31+
else
32+
{
33+
// we can jump to this cell by two ways(⬇️ and ↘️)
34+
dp[i].push_back(min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle[i][j]);
35+
}
36+
}
37+
}
38+
// returning the minimum out of all calculated sums
39+
return *min_element(dp[n - 1].begin(), dp[n - 1].end());
40+
}
41+
int main()
42+
{
43+
int n;
44+
cin >> n;
45+
vector<vector<int>> triangle(n);
46+
for (int i = 0; i < n; i++)
47+
{
48+
for (int j = 0; j <= i; j++)
49+
{
50+
int x;
51+
cin >> x;
52+
triangle[i].push_back(x);
53+
}
54+
}
55+
cout << minimumTotal(triangle);
56+
}
57+
58+
// Sample Inputs
59+
60+
// Sample Inputs
61+
62+
// Sample Inputs
63+
64+
// 4
65+
// 2
66+
// 3 4
67+
// 6 5 7
68+
// 4 1 8 3
69+
70+
// 1
71+
// -10
72+
73+
// Corresponding Outputs
74+
75+
// 11
76+
77+
// -10

0 commit comments

Comments
 (0)