• 931. Minimum Falling Path Sum


    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 <= A.length == A[0].length <= 100
        -100 <= A[i][j] <= 100
    

    Accepted
    5,997
    Submissions
    10,729

    Solution1:(TLE)

    class Solution:
        def minFallingPathSum(self, A):
            """
            :type A: List[List[int]]
            :rtype: int
            """
            res = 99999999
            l = len(A)
            def solve(i,j,sum):
                nonlocal res
                if i==l-1:
                    # print(sum)
                    res = min(res,sum)
                else:
                    solve(i+1,j,sum+A[i+1][j])
                    if j>0:
                        solve(i+1,j-1,sum+A[i+1][j-1])
                    if j<l-1:
                        solve(i+1,j+1,sum+A[i+1][j+1])
            for i in range(l):
                solve(0,i,A[0][i])
            return res
    

    36 / 46 test cases passed.

    这样求出每条到最后一行的路径的方法时间复杂度较大,在每一行时,只使用到这个点的最小路径。

    Solution2:

    class Solution:
        def minFallingPathSum(self, A):
            """
            :type A: List[List[int]]
            :rtype: int
            """
            dp = [[0 for i in range(len(A))] for j in range(len(A))]
            for i in range(len(A)):
                for j in range(len(A)):
                    if i==0:
                        dp[i][j] = A[i][j]
                        continue
                    temp = A[i][j] + dp[i-1][j]
                    if j>0:
                        temp = min(temp,A[i][j] + dp[i-1][j-1])
                    if j<len(A)-1:
                        temp = min(A[i][j] + dp[i - 1][j+1],temp)
                    dp[i][j] = temp
            return min(dp[-1][j] for j in range(len(A)))
    
  • 相关阅读:
    js调用后台方法
    Js 实现trim方法
    Service获取客户端IP地址(java)
    ASP.NET中页面传值
    Asp.net 实现选择文件批量下载
    js调用后台代码
    获取webservice客户端IP地址 (C# java )
    使 WebBrowser 更简单的新加和执行 js, 可安装 jQuery 脚本的 C# 开源代码 IEBrowse...
    Mac下各种网络命令的使用
    Java关键字
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/10049759.html
Copyright © 2020-2023  润新知