【DP】931. 下降路径最小和

题目

法1:标准DP

class Solution {
    public int minFallingPathSum(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        int m = matrix.length, n = matrix[0].length;
        int[][] dp = new int[m][n]; // 到达i,j的最小路径和
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < n; ++i) { // 首行
            dp[0][i] = matrix[0][i];
            if (m == 1) {
                min = Math.min(min, dp[0][i]);
            }
        }
        
        for (int i = 1; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                int preMin = dp[i - 1][j];
                if (j - 1 >= 0) {
                    preMin = Math.min(preMin, dp[i - 1][j - 1]);
                }
                if (j + 1 < n) {
                    preMin = Math.min(preMin, dp[i - 1][j + 1]);
                }
                dp[i][j] = preMin + matrix[i][j];
                if (i == m - 1) {
                    min = Math.min(min, dp[i][j]);
                }
            }
        }

        return min;
    }
}

你可能感兴趣的:(dp)