931. Minimum Falling Path Sum
Posted bernieloveslife
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)))
以上是关于931. Minimum Falling Path Sum的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode: Minimum Falling Path Sum
leetcode1289. Minimum Falling Path Sum II
108th LeetCode Weekly Contest Minimum Falling Path Sum
LeetCode 5129. 下降路径最小和 II Minimum Falling Path Sum II
Falling back to java on path. This behavior is deprecated
spring boot 运行提示:No active profile set, falling back to default profiles: default