Skip to content

Commit 42a3808

Browse files
author
weiy
committed
minimum falling path sum medium
1 parent 0faf18d commit 42a3808

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Array/MinimumFallingPathSum.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
Given a square array of integers A, we want the minimum sum of a falling path through A.
3+
4+
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.
5+
6+
7+
8+
Example 1:
9+
10+
Input: [[1,2,3],[4,5,6],[7,8,9]]
11+
Output: 12
12+
Explanation:
13+
The possible falling paths are:
14+
[1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]
15+
[2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]
16+
[3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]
17+
The falling path with the smallest sum is [1,4,7], so the answer is 12.
18+
19+
20+
21+
Note:
22+
23+
1. 1 <= A.length == A[0].length <= 100
24+
2. -100 <= A[i][j] <= 100
25+
26+
27+
28+
从上到下,每下层元素可以选择位于它之上的 左中右 三个元素。
29+
30+
直接 Dp 思路:
31+
从第二层开始,每个元素都选择位于它之上的三个元素中最小的一个元素。
32+
最后输出最后一层中最小的元素即可。
33+
34+
测试地址:
35+
https://leetcode.com/contest/weekly-contest-108/problems/minimum-falling-path-sum/
36+
37+
"""
38+
class Solution(object):
39+
def minFallingPathSum(self, A):
40+
"""
41+
:type A: List[List[int]]
42+
:rtype: int
43+
"""
44+
45+
for y in range(1, len(A)):
46+
for x in range(len(A[0])):
47+
a = A[y-1][x-1] if x-1 >= 0 else float('inf')
48+
b = A[y-1][x+1] if x+1 < len(A[0]) else float('inf')
49+
50+
A[y][x] += min(A[y-1][x], a, b)
51+
52+
return min(A[-1])

0 commit comments

Comments
 (0)