Skip to content

Commit 61830fe

Browse files
committed
Time: 678 ms (49.88%), Space: 257 MB (18.43%) - LeetHub
1 parent fa5ea88 commit 61830fe

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
public:
3+
int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
4+
5+
int m = matrix.size();
6+
int n = matrix[0].size();
7+
8+
// prefix sum
9+
10+
for(int row = 0; row < m; ++row)
11+
{
12+
for(int col = 1; col < n; ++col)
13+
{
14+
matrix[row][col] += matrix[row][col-1];
15+
}
16+
}
17+
18+
int count = 0;
19+
20+
// fix 2 colums
21+
22+
for(int c1 = 0; c1 < n; ++c1)
23+
{
24+
for(int c2 = c1; c2 < n; ++c2)
25+
{
26+
unordered_map<int,int> mp;
27+
int sum = 0;
28+
mp.insert({0,1});
29+
30+
for(int row = 0; row < m; ++row)
31+
{
32+
sum += matrix[row][c2] - (c1 > 0 ? matrix[row][c1-1] : 0);
33+
count += mp[sum-target];
34+
35+
if(mp.find(sum) != mp.end())
36+
++mp[sum];
37+
else
38+
mp[sum] = 1;
39+
}
40+
}
41+
}
42+
43+
return count;
44+
}
45+
};

0 commit comments

Comments
 (0)