Skip to content

Commit cb8b064

Browse files
committed
Leetcode 1074 Number of Submatrices That Sum to Target
1 parent c8941c3 commit cb8b064

File tree

1 file changed

+21
-25
lines changed

1 file changed

+21
-25
lines changed
Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,26 @@
11
class Solution {
2-
public int numSubmatrixSumTarget(int[][] matrix, int target) {
3-
int m = matrix.length+1, n = matrix[0].length+1;
4-
5-
// compute 2D prefix sum with padding
6-
int[][] ps = new int[m][n];
7-
for (int i = 1; i < m; i++) {
8-
for (int j = 1; j < n; j++) {
9-
ps[i][j] = ps[i - 1][j] + ps[i][j - 1] - ps[i - 1][j - 1] + matrix[i - 1][j - 1];
10-
}
11-
}
2+
public int numSubmatrixSumTarget(int[][] matrix, int target) {
3+
int m = matrix.length+1, n = matrix[0].length+1;
4+
int[][] presum = new int[m][n];
5+
for(int i=1;i<m;i++) {
6+
for(int j=1;j<n;j++) {
7+
presum[i][j] = presum[i-1][j] + presum[i][j-1] - presum[i-1][j-1] + matrix[i-1][j-1];
8+
}
9+
}
1210

13-
int ans = 0, currSum;
14-
Map<Integer, Integer> map = new HashMap();
15-
16-
for (int row = 1; row < m; row++) {
17-
for (int row2 = row; row2 < m; row2++) {
18-
map.clear();
19-
map.put(0, 1);
20-
for (int col = 1; col < n; col++) {
21-
currSum = ps[row2][col] - ps[row - 1][col];
22-
ans += map.getOrDefault(currSum - target, 0);
23-
map.put(currSum, map.getOrDefault(currSum, 0) + 1);
11+
int ans = 0;
12+
for(int startRow=1;startRow<m;startRow++) {
13+
for(int endRow=startRow;endRow<m;endRow++) {
14+
Map<Integer,Integer> map = new HashMap<>();
15+
map.put(0,1);
16+
for(int col=1;col<n;col++) {
17+
int currSum = presum[endRow][col] - presum[startRow-1][col];
18+
ans += map.getOrDefault(currSum - target, 0);
19+
map.put(currSum, map.getOrDefault(currSum, 0)+1);
20+
}
21+
}
2422
}
25-
}
26-
}
23+
return ans;
2724

28-
return ans;
29-
}
25+
}
3026
}

0 commit comments

Comments
 (0)