Leetcode 931:下降路径最小和(最详细的解法!!!)

版权声明:本文为博主原创文章,未经博主允许不得转载。有事联系:[email protected] https://blog.csdn.net/qq_17550379/article/details/83536212

给定一个方形整数数组 A,我们想要得到通过 A下降路径最小和。

下降路径可以从第一行中的任何元素开始,并从每一行中选择一个元素。在下一行选择的元素和当前行所选元素最多相隔一列。

示例:

输入:[[1,2,3],[4,5,6],[7,8,9]]
输出:12
解释:
可能的下降路径有:
  • [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]

和最小的下降路径是 [1,4,7],所以答案是 12

提示:

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

解题思路

这个问题就是之前Leetcode 120:三角形最小路径和(最详细的解法!!!)非常类似。所以我们直接使用之前的方法就可以解决这个问题。

class Solution:
    def minFallingPathSum(self, A):
        """
        :type A: List[List[int]]
        :rtype: int
        """
        if not A:
            return 0

        r, c = len(A), len(A[0])
        for row in range(r - 1, 0, -1):
            for col in range(c):
                if col == 0:
                    A[row - 1][col] += min(A[row][col], A[row][col + 1])
                elif col == c - 1:
                    A[row - 1][col] += min(A[row][col], A[row][col - 1])
                else:
                    A[row - 1][col] += min(A[row][col], A[row][col + 1], A[row][col - 1])

        return min(A[0])

我们还有一种更简洁的写法。

class Solution:
    def minFallingPathSum(self, A):
        """
        :type A: List[List[int]]
        :rtype: int
        """
        while len(A) >= 2:
            row = A.pop()            
            for i in range(len(row)):
                A[-1][i] += min(row[max(0,i-1): min(len(row), i+2)])
        return min(A[0])

reference:

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

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/83536212