-
Notifications
You must be signed in to change notification settings - Fork 0
/
TRIANGLE
42 lines (35 loc) · 1.25 KB
/
TRIANGLE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Given a triangle array, return the minimum path sum from top to bottom.
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.
Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
Example 2:
Input: triangle = [[-10]]
Output: -10
import java.util.List;
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
// Convert the triangle to a 2D array for easier manipulation
int[][] dp = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
dp[i][j] = triangle.get(i).get(j);
}
}
// Calculate the minimum path sum using bottom-up approach
for (int i = n - 2; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
dp[i][j] += Math.min(dp[i + 1][j], dp[i + 1][j + 1]);
}
}
return dp[0][0]; // The top element contains the minimum path sum
}
}