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:

``````Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output: 4
Explanation: The four 1x1 submatrices that only contain 0.
``````

Example 2:

``````Input: matrix = [[1,-1],[-1,1]], target = 0
Output: 5
Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
``````

Example 3:

``````Input: matrix = [[904]], target = 0
Output: 0
``````

Constraints:

• `1 <= matrix.length <= 100`
• `1 <= matrix[0].length <= 100`
• `-1000 <= matrix[i] <= 1000`
• `-10^8 <= target <= 10^8`

``````class Solution {
public:
int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
int res = 0, m = matrix.size(), n = matrix[0].size();
vector<vector<int>> sums(m + 1, vector<int>(n + 1));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
sums[i][j] = sums[i][j - 1] + sums[i - 1][j] - sums[i - 1][j - 1] + matrix[i - 1][j - 1];
}
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
for (int p = 1; p <= i; ++p) {
for (int q = 1; q <= j; ++q) {
int t = sums[i][j] - sums[i][q - 1] - sums[p - 1][j] + sums[p - 1][q - 1];
if (t == target) ++res;
}
}
}
}
return res;
}
};
``````

``````class Solution {
public:
int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
int res = 0, m = matrix.size(), n = matrix[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 1; j < n; ++j) {
matrix[i][j] += matrix[i][j - 1];
}
}
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
unordered_map<int, int> cntMap{{0, 1}};
int cur = 0;
for (int k = 0; k < m; ++k) {
cur += matrix[k][j] - (i > 0 ? matrix[k][i - 1] : 0);
res += cntMap[cur - target];
++cntMap[cur];
}
}
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1074

Subarray Sum Equals K

Max Sum of Rectangle No Larger Than K

Two Sum

https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/

https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/303750/JavaC%2B%2BPython-Find-the-Subarray-with-Target-Sum

https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/303773/C%2B%2B-O(n3)-Simple-1D-Subarray-target-sum-applied-to-2D-array

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation