All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0101_0200.s0120_triangle.Solution Maven / Gradle / Ivy

There is a newer version: 1.37
Show newest version
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;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy