其他分享
首页 > 其他分享> > 每日一道Leetcode - 931. 下降路径最小和【动态规划】

每日一道Leetcode - 931. 下降路径最小和【动态规划】

作者:互联网

在这里插入图片描述

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;
    }
}

标签:不超,min,int,路径,Math,ans,931,Leetcode,best
来源: https://blog.csdn.net/weixin_41041275/article/details/111604770