g0101_0200.s0120_triangle.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0101_0200.s0120_triangle;
// #Medium #Array #Dynamic_Programming #Algorithm_I_Day_12_Dynamic_Programming
// #Dynamic_Programming_I_Day_13 #2022_02_22_Time_1_ms_(99.76%)_Space_41.7_MB_(43.52%)
import java.util.Arrays;
import java.util.List;
public class Solution {
public int minimumTotal(List> triangle) {
if (triangle == null || triangle.isEmpty()) {
return 0;
}
int[][] dp = new int[triangle.size()][triangle.get(triangle.size() - 1).size()];
for (int[] temp : dp) {
Arrays.fill(temp, -10001);
}
return dfs(triangle, dp, 0, 0);
}
private int dfs(List> triangle, int[][] dp, int row, int col) {
if (row >= triangle.size()) {
return 0;
}
if (dp[row][col] != -10001) {
return dp[row][col];
}
int sum =
triangle.get(row).get(col)
+ Math.min(
dfs(triangle, dp, row + 1, col),
dfs(triangle, dp, row + 1, col + 1));
dp[row][col] = sum;
return sum;
}
}