Skip to content

Commit 164c560

Browse files
authored
minFallingPathSumTriangle.cpp created (codewithdev#130)
2 parents 5fdac30 + a4673b0 commit 164c560

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
// Sample Inputs
6+
// 4
7+
// 2
8+
// 3 4
9+
// 6 5 7
10+
// 4 1 8 3
11+
// 1
12+
// -10
13+
14+
// Corresponding Outputs
15+
// 11
16+
// -10
17+
18+
#include <bits/stdc++.h>
19+
using namespace std;
20+
21+
// recursive function
22+
int minimumTotal(vector<vector<int>> &triangle)
23+
{
24+
int n = triangle.size();
25+
vector<vector<int>> dp(n);
26+
for (int i = 0; i < n; i++)
27+
{
28+
for (int j = 0; j < triangle[i].size(); j++)
29+
{
30+
if (i == 0 and j == 0)
31+
{
32+
// very first cell
33+
dp[i].push_back(triangle[i][j]);
34+
}
35+
else if (j == 0)
36+
{
37+
// we can jump to this cell by one way(⬇️)
38+
dp[i].push_back(dp[i - 1][j] + triangle[i][j]);
39+
}
40+
else if (j == (triangle[i].size() - 1))
41+
{
42+
// we can jump to this cell by one way(↘️)
43+
dp[i].push_back(dp[i - 1][j - 1] + triangle[i][j]);
44+
}
45+
else
46+
{
47+
// we can jump to this cell by two ways(⬇️ and ↘️)
48+
dp[i].push_back(min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle[i][j]);
49+
}
50+
}
51+
}
52+
// returning the minimum out of all calculated sums
53+
return *min_element(dp[n - 1].begin(), dp[n - 1].end());
54+
}
55+
int main()
56+
{
57+
int n;
58+
cin >> n;
59+
vector<vector<int>> triangle(n);
60+
for (int i = 0; i < n; i++)
61+
{
62+
for (int j = 0; j <= i; j++)
63+
{
64+
int x;
65+
cin >> x;
66+
triangle[i].push_back(x);
67+
}
68+
}
69+
cout << minimumTotal(triangle);
70+
}

0 commit comments

Comments
 (0)