leetcode-1074-Number of Submatrices That Sum to Target
问题
Given a matrix, and a target, return the number of non-empty submatrices that sum to target.
A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.
Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.
Example 1:
1 | Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 |
Example 2:
1 | Input: matrix = [[1,-1],[-1,1]], target = 0 |
Note:
1 <= matrix.length <= 3001 <= matrix[0].length <= 300-1000 <= matrix[i] <= 1000-10^8 <= target <= 10^8
分析
先对每一行求前缀和,然后再确定每一对可能的列,这样在确定了每一列求解时,就转化为了Find the Subarray with Target Sum 的问题。时间复杂度$O(N^2M)$。
总结:二维数组中查找子矩阵的处理方案除了固定每个右下角再进行子问题分解之外,还可以通过固定每两个确定的行或者列来分解子问题,思路与之前一道查找四个顶点都是 1 的 submatrix 的题目的处理方法比较像。
代码
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/30/leetcode-1074/
License: 知识共享署名-非商业性使用 4.0 国际许可协议