diff --git "a/05-\345\212\250\346\200\201\350\247\204\345\210\222/problem_solving_01.py" "b/05-\345\212\250\346\200\201\350\247\204\345\210\222/problem_solving_01.py" new file mode 100644 index 0000000000000000000000000000000000000000..d7191750657026a4486f782b060dce9acfd4d393 --- /dev/null +++ "b/05-\345\212\250\346\200\201\350\247\204\345\210\222/problem_solving_01.py" @@ -0,0 +1,41 @@ +""" +下降路径最小和 +""" +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)