File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
1074-number-of-submatrices-that-sum-to-target Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments