fix:下降路径最小和

上级 df87473e
"""
下降路径最小和
"""
from linecache import cache
from math import inf
from typing import List
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
"""
动态规划:
选或者不选?
枚举选哪个?
这道题使用枚举选哪个
:param matrix:
:return:
"""
n = len(matrix)
@cache
def dfs(line: int, i: int) -> int:
"""
每一个到顶层的路径和最小值
:param line: 行号
:param i: 列index
:return:
"""
if i < 0 or i >= n:
return inf
if line == 0:
# 递归结束条件,到达顶层
return matrix[0][i]
return min(dfs(line - 1, i - 1), dfs(line - 1, i), dfs(line - 1, i + 1)) + matrix[line][i]
return min(dfs(n - 1, index) for index in range(n))
if __name__ == '__main__':
result = Solution().minFallingPathSum([[2, 1, 3], [6, 5, 4], [7, 8, 9]])
print(result)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册