码迷,mamicode.com
首页 > 其他好文 > 详细

931. Minimum Falling Path Sum

时间:2018-12-01 16:57:22      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:tput   put   imu   accept   nonlocal   array   code   ted   continue   

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)))

931. Minimum Falling Path Sum

标签:tput   put   imu   accept   nonlocal   array   code   ted   continue   

原文地址:https://www.cnblogs.com/bernieloveslife/p/10049759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!