LeetCode5852.最小化目标值与所选元素的差(动态规划)

  • 题目:

5852. 最小化目标值与所选元素的差

https://leetcode-cn.com/contest/weekly-contest-255/problems/minimize-the-difference-between-target-and-chosen-elements/

给定 m × n 的矩阵,以及整数 target

从矩阵每行任选一个数,这 m 个数的总和,与 target 的差值绝对值最小

  • 题解:

如果采用深度优先搜索,时间复杂度为 O(n^{m}),会超时

考虑到数据范围:

  • 1 <= m, n <= 70
  • 1 <= mat[i][j] <= 70

所以求解过程中有很多重复状态,使用动态规划让重复状态只算一次

动态规划的时间复杂度是 O(70^{3}) 

  • 源码:
class Solution:
    def minimizeTheDifference(self, mat: list[list[int]], target: int) -> int:
        m = len(mat)
        n = len(mat[0])

        visited = set(mat[0])

        for mi in range(1, m):
            newv = set(v + d for d in mat[mi] for v in visited)
            visited = newv
        
        return min(abs(target - v) for v in visited)


if __name__ == "__main__":
    print(Solution().minimizeTheDifference(mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13))
    print(Solution().minimizeTheDifference(mat = [[1],[2],[3]], target = 100))
    print(Solution().minimizeTheDifference(mat = [[1,2,9,8,7]], target = 6))

你可能感兴趣的:(算法和数据结构,LeetCode,python,动态规划)