Skip to content

Commit b445009

Browse files
authored
Merge pull request #4169 from NAVJOT-786/main
Create 0120-triangle leetcode solution
2 parents 7a38481 + 83f7f63 commit b445009

File tree

1 file changed

+188
-0
lines changed

1 file changed

+188
-0
lines changed
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
---
2+
id: Min-falling-path-sum-in-a-Triangle
3+
title: Min falling path sum in a Triangle
4+
sidebar_label: 120-Min falling path sum in a Triangle
5+
tags:
6+
- Recursion
7+
- Dynamic Programming
8+
- Java
9+
- Cpp
10+
- Python
11+
description: "Given a triangular type matrix we need to return the minimum sum for reaching the bottom from the top . in each step we can either move down or diagonally right"
12+
---
13+
14+
## Problem
15+
16+
Given a triangle array, return the minimum path sum from top to bottom.
17+
18+
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
19+
20+
### Examples
21+
22+
**Example 1:**
23+
24+
**Input:** triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
25+
**Output:** 11
26+
**Explanation:** The triangle looks like:
27+
2
28+
3 4
29+
6 5 7
30+
4 1 8 3
31+
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
32+
33+
**Example 2:**
34+
35+
**Input:** triangle = [[-10]]
36+
**Output:** -10
37+
38+
### Constraints
39+
40+
- `1 <= triangle.length <= 200`
41+
- `triangle[0].length == 1`
42+
- `triangle[i].length == triangle[i - 1].length + 1`
43+
- `-104 <= triangle[i][j] <= 104`
44+
45+
46+
---
47+
48+
## Approach
49+
50+
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.
51+
52+
### Steps:
53+
54+
Step 1: Initialize the Memoization Table
55+
56+
Create a 2D array dp of size n x n, where n is the number of rows in the triangle. Initialize all elements in dp to INT_MAX (or a large negative number) except for the first row, which is set to the corresponding elements in the input triangle.
57+
58+
Step 2: Fill the Memoization Table
59+
60+
Iterate through each cell in the triangle, starting from the second row. For each cell (i, j), calculate the minimum sum of the falling path that ends at this cell by considering the two possible paths:
61+
62+
Directly below: (i+1, j)
63+
Diagonally right: (i+1, j+1)
64+
Update dp[i][j] with the minimum sum of these three paths.
65+
66+
Step 3: Return the Minimum Falling Path Sum
67+
68+
The minimum falling path sum is the minimum value in the last row of the dp table.
69+
### Solution
70+
71+
#### Java Solution
72+
73+
```java
74+
class Solution {
75+
public int minimumTotal(List<List<Integer>> triangle) {
76+
int n = triangle.size();
77+
int[][] dp = new int[n][n];
78+
79+
// Initialize the dp array with a large value
80+
for (int i = 0; i < n; i++) {
81+
for (int j = 0; j < n; j++) {
82+
dp[i][j] = Integer.MAX_VALUE;
83+
}
84+
}
85+
// Recursive function with memoization
86+
return f(triangle, 0, 0, dp);
87+
}
88+
private int f(List<List<Integer>> triangle, int i, int j, int[][] dp) {
89+
int n = triangle.size();
90+
if (i == n - 1) {
91+
return triangle.get(i).get(j);
92+
}
93+
if (dp[i][j] != Integer.MAX_VALUE) {
94+
return dp[i][j];
95+
}
96+
int down = triangle.get(i).get(j) + f(triangle, i + 1, j, dp);
97+
int diag = triangle.get(i).get(j) + f(triangle, i + 1, j + 1, dp);
98+
dp[i][j] = Math.min(down, diag);
99+
return dp[i][j];
100+
}
101+
public static void main(String[] args) {
102+
Solution solution = new Solution();
103+
List<List<Integer>> triangle = new ArrayList<>();
104+
triangle.add(List.of(2));
105+
triangle.add(List.of(3, 4));
106+
triangle.add(List.of(6, 5, 7));
107+
triangle.add(List.of(4, 1, 8, 3));
108+
System.out.println(solution.minimumTotal(triangle)); // Output: 11
109+
}
110+
}
111+
112+
113+
```
114+
### C++ Solution
115+
116+
```cpp
117+
class Solution {
118+
public:
119+
int minimumTotal(vector<vector<int>>& triangle) {
120+
int n = triangle.size();
121+
vector<vector<int>> dp(n, vector<int>(n, INT_MAX));
122+
123+
function<int(int, int)> f = [&](int i, int j) -> int {
124+
if (i == n - 1) {
125+
return triangle[i][j];
126+
}
127+
if (dp[i][j] != INT_MAX) {
128+
return dp[i][j];
129+
}
130+
int down = triangle[i][j] + f(i + 1, j);
131+
int diag = triangle[i][j] + f(i + 1, j + 1);
132+
return dp[i][j] = min(down, diag);
133+
};
134+
135+
return f(0, 0);
136+
}
137+
};
138+
139+
```
140+
### Python Solution
141+
142+
```python
143+
class Solution:
144+
def minimumTotal(self, triangle: List[List[int]]) -> int:
145+
n = len(triangle)
146+
dp = [[float('inf')] * n for _ in range(n)]
147+
148+
def f(i: int, j: int) -> int:
149+
if i == n - 1:
150+
return triangle[i][j]
151+
if dp[i][j] != float('inf'):
152+
return dp[i][j]
153+
down = triangle[i][j] + f(i + 1, j)
154+
diag = triangle[i][j] + f(i + 1, j + 1)
155+
dp[i][j] = min(down, diag)
156+
return dp[i][j]
157+
158+
return f(0, 0)
159+
```
160+
### javascript Solution
161+
162+
```javascript
163+
var minimumTotal = function(triangle) {
164+
165+
let n = triangle.length;
166+
let dp = Array(n).fill(Number.MAX_VALUE).map(()=> Array(n).fill(Number.MAX_VALUE));
167+
//let min = Number.MAX_VALUE;
168+
function f(i, j){
169+
170+
if(i == n-1){return triangle[i][j];}
171+
if(dp[i][j] != Number.MAX_VALUE) return dp[i][j];
172+
let down = triangle[i][j] + f(i+1, j);
173+
174+
let diag = triangle[i][j] + f(i+1, j+1);
175+
return dp[i][j] = Math.min(down, diag);
176+
}
177+
return f(0, 0);
178+
};
179+
```
180+
### Complexity Analysis
181+
**Time Complexity:** O(n * m)
182+
>where n and m are no of rows and no of columns respectively.
183+
184+
**Space Complexity:** O(n*n)
185+
>Reason: We are using the extra space in the form of dp array.
186+
187+
### References
188+
**LeetCode Problem:** Min falling path sum in a triangle

0 commit comments

Comments
 (0)