[LeetCode] 931. Minimum Falling Path Sum

题:https://leetcode.com/problems/minimum-falling-path-sum/description/

题目

Given a square array of integers A, we want the minimum sum of a falling path through A.

A falling path starts at any element in the first row, and chooses one element from each row. The next row’s choice must be in a column that is different from the previous row’s column by at most one.

Example 1:

Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: 12
Explanation: 
The possible falling paths are:
[1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]
[2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]
[3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]
The falling path with the smallest sum is [1,4,7], so the answer is 12.

Note:

  1. 1 <= A.length == A[0].length <= 100
  2. -100 <= A[i][j] <= 100-100 <= A[i][j] <= 100

题目大意

从 矩阵A[][] 第一行出发,求到 最后一行的最短距离。A从一行到另一行时,选择的col 与 当前 col 差不能超过1。

思路

动态规划

状态 dp[i][j]:从出发到 A[i+1][j]的最短距离。
状态初始化:dp[0][j] = 0。 便于 书写 状态转移方程。

状态转移方程:
即,dp[i][j] = min(dp[i-1][j-1],dp[i-1][j],dp[i-1][j+1]) + A[i-1][j];
因为,从A[i-1][j-1],A[i-1][j],A[i-1][j+1] 都可以到达 A[i][j]。

最后取 dp[A.length][j] 中最小值为最短路径。

                dp[i][j] =dp[i-1][j];
                if(j-1>=0)
                    dp[i][j] = Math.min(dp[i][j],dp[i-1][j-1]);
                if(j+1<dp[0].length)
                    dp[i][j] = Math.min(dp[i][j],dp[i-1][j+1]);
                dp[i][j] = dp[i][j] + A[i-1][j];

code

class Solution {
    public int minFallingPathSum(int[][] A) {
        int[][] dp =  new int[A.length+1][A[0].length];
        for(int i = 1;i<dp.length;i++){
            for(int j =0;j<dp[0].length;j++){
                dp[i][j] =dp[i-1][j];
                if(j-1>=0)
                    dp[i][j] = Math.min(dp[i][j],dp[i-1][j-1]);
                if(j+1<dp[0].length)
                    dp[i][j] = Math.min(dp[i][j],dp[i-1][j+1]);
                dp[i][j] = dp[i][j] + A[i-1][j];
            }
        }
        int res = 100*100;
        for(int j =0;j<dp[0].length;j++){
            res = Math.min(res,dp[dp[0].length][j]);
        }
        return res;
    }
}

由于 dp[i][j] 只用到 dp[i-1][j-1],dp[i-1][j],dp[i-1][j+1] ,所以 不需要多维。

但 由于 dp[i][j] 用到了 dp[i-1][j-1] ,前个状态的保存不能只用一维度,需要单独保存前一行的所有状态。

使用dp[0][j] 保存前一行状态,dp[1][j] 为新状态。

class Solution {
    public int minFallingPathSum(int[][] A) {
        int [][]dp = new int[2][A[0].length];
        for(int i = 0;i<A.length;i++){
            for(int j = 0;j<A[0].length;j++){
                if(j-1>=0)
                    dp[1][j] = Math.min(dp[1][j],dp[0][j-1]);
                if(j+1<A[0].length)
                    dp[1][j] = Math.min(dp[1][j],dp[0][j+1]);
                dp[1][j] += A[i][j];
            }
            for(int j = 0;j<A[0].length;j++)
                dp[0][j] = dp[1][j];
        }
        int res = dp[1][0];
        for(int j = 1 ;j<A[0].length;j++)
            res = Math.min(res,dp[1][j]);
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/83477067