-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Leetcode 1074 Number of Submatrices That Sum to Target
- Loading branch information
1 parent
c8941c3
commit cb8b064
Showing
1 changed file
with
21 additions
and
25 deletions.
There are no files selected for viewing
46 changes: 21 additions & 25 deletions
46
1074_Number of Submatrices That Sum to Target/NumberofSubmatricesThatSumtoTarget2.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |