Un Leetcode por día: 931. Ruta de descenso mínima [Programación dinámica]

Inserte la descripción de la imagen aquí

class Solution {
    
    
    public int minFallingPathSum(int[][] A) {
    
    
        // 动态规划问题
        // 可选择的路径只有上一行的j,j-1.j+1位置,取最小
        // 注意是方形数组,所以只需要有一个变量N即可
        int N = A.length;
        int ans = Integer.MAX_VALUE;
        
        for(int i = N-1-1;i>=0;i--){
    
    
            // 从倒数第二行开始,在下面一行的最好的值的基础上更新当前行,自底向上
            for(int j = 0;j<N;j++){
    
    
                int best = A[i+1][j];
                if(j>0){
    
    
                    // 保证左边界不超
                    best = Math.min(best,A[i+1][j-1]);
                }
                if(j<N-1){
    
    
                    // 保证右边界不超
                    best = Math.min(best,A[i+1][j+1]);
                }
                A[i][j] += best;
            }
        }
        // 从第一行选择最小值为结果
        for(int x:A[0]){
    
    
            ans = Math.min(ans,x);
        }
        return ans;
    }
}

Supongo que te gusta

Origin blog.csdn.net/weixin_41041275/article/details/111604770
Recomendado
Clasificación