Skip to content

Commit 8441107

Browse files
authored
Create 1074. Number of Submatrices That Sum to Target
1 parent 38d4cb5 commit 8441107

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Diff for: 1074. Number of Submatrices That Sum to Target

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public int numSubmatrixSumTarget(int[][] matrix, int target) {
3+
int m = matrix.length,n=matrix[0].length;
4+
5+
for(int row =0;row<m;row++){
6+
for(int col=1;col<n;col++){
7+
matrix[row][col]+=matrix[row][col-1];
8+
}
9+
}
10+
11+
int count=0;
12+
13+
for(int c1=0;c1<n;c1++){
14+
for(int c2=c1;c2<n;c2++){
15+
16+
Map<Integer,Integer> map = new HashMap<>();
17+
map.put(0,1);
18+
int sum=0;
19+
20+
for(int row=0;row<m;row++){
21+
sum += matrix[row][c2] - (c1>0 ? matrix[row][c1-1] : 0);
22+
count += map.getOrDefault(sum-target,0);
23+
map.put(sum,map.getOrDefault(sum,0)+1);
24+
}
25+
26+
}
27+
}
28+
29+
return count;
30+
}
31+
}

0 commit comments

Comments
 (0)