LC 931. Minimum Falling Path Sum

1.题目描述

931. Minimum Falling Path Sum

Medium

11311

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

题目大概意思就是说找一条最短的下落路径,所谓下落路径要满足这样的条件:从第一行任意一个元素开始,每行都要选择一个元素。下一行所选元素的列和上一行所选元素的列最多相差1.

2.解题思路

用动态规划解题。

用一个二维数组 int dp[ROW_NUM][COL_NUM]记录过程。其中dp[i][j]表示到达(i,j)这个点的最短路径长度。那么根据题意,就有 dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i-1][j+1])+(i,j)这一点本身的数值。dp数组第一行初始化为所给矩阵的第一行,然后用两个for循环完成对dp数组的全部赋值。最后找出dp数组最后一行最小的数并返回即可。

3.实现代码

class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& A) {
        int sum = 0;
        int dp[100][100];
        memset(dp, 0, sizeof(dp));
        int row = A.size();
        int col = A.size();
        for (int i=0; i<row; i++) {
            dp[0][i] = A[0][i];
        }
        for (int cur_row = 1; cur_row<row; cur_row++) {
            for (int cur_col=0; cur_col<col; cur_col++) {
                if (cur_col-1 < 0) {
                    dp[cur_row][cur_col] = min(dp[cur_row-1][cur_col], dp[cur_row-1][cur_col+1]) + A[cur_row][cur_col];
                }
                else if (cur_col+1 > col-1) {
                    dp[cur_row][cur_col] = min(dp[cur_row-1][cur_col], dp[cur_row-1][cur_col-1]) + A[cur_row][cur_col];
                }
                else {
                     dp[cur_row][cur_col] = min(min(dp[cur_row-1][cur_col], dp[cur_row-1][cur_col-1]),dp[cur_row-1][cur_col+1] ) + A[cur_row][cur_col];
                }
            }
        }
        sum = dp[row-1][0];
        for (int i=0; i<col; i++) {
            sum = min(dp[row-1][i], sum);
        }
        return sum;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41814429/article/details/84951107