Skip to content

Commit

Permalink
Leetcode 1074 Number of Submatrices That Sum to Target
Browse files Browse the repository at this point in the history
  • Loading branch information
jiajionline committed Oct 1, 2023
1 parent c8941c3 commit cb8b064
Showing 1 changed file with 21 additions and 25 deletions.
Original file line number Diff line number Diff line change
@@ -1,30 +1,26 @@
class Solution {
public int numSubmatrixSumTarget(int[][] matrix, int target) {
int m = matrix.length+1, n = matrix[0].length+1;

// compute 2D prefix sum with padding
int[][] ps = new int[m][n];
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
ps[i][j] = ps[i - 1][j] + ps[i][j - 1] - ps[i - 1][j - 1] + matrix[i - 1][j - 1];
}
}
public int numSubmatrixSumTarget(int[][] matrix, int target) {
int m = matrix.length+1, n = matrix[0].length+1;
int[][] presum = new int[m][n];
for(int i=1;i<m;i++) {
for(int j=1;j<n;j++) {
presum[i][j] = presum[i-1][j] + presum[i][j-1] - presum[i-1][j-1] + matrix[i-1][j-1];
}
}

int ans = 0, currSum;
Map<Integer, Integer> map = new HashMap();

for (int row = 1; row < m; row++) {
for (int row2 = row; row2 < m; row2++) {
map.clear();
map.put(0, 1);
for (int col = 1; col < n; col++) {
currSum = ps[row2][col] - ps[row - 1][col];
ans += map.getOrDefault(currSum - target, 0);
map.put(currSum, map.getOrDefault(currSum, 0) + 1);
int ans = 0;
for(int startRow=1;startRow<m;startRow++) {
for(int endRow=startRow;endRow<m;endRow++) {
Map<Integer,Integer> map = new HashMap<>();
map.put(0,1);
for(int col=1;col<n;col++) {
int currSum = presum[endRow][col] - presum[startRow-1][col];
ans += map.getOrDefault(currSum - target, 0);
map.put(currSum, map.getOrDefault(currSum, 0)+1);
}
}
}
}
}
return ans;

return ans;
}
}
}

0 comments on commit cb8b064

Please sign in to comment.