思路
- sum[x][y]表示从第1行第1列到第x行(注意 此处行列从1开始计数)第y列的元素数值和
- 起始y(startY)和终止y(endY)分别变化,内嵌套for循环进行x的变化
- 哈希表记录每个矩阵的元素和 所以当此时target - 矩阵元素和的元素在哈希表中存在,说明一个大矩阵减去有重合部分的小矩阵得到一个新的小矩阵,这个小矩阵的值等于目标值
代码实现
public static int numSubmatrixSumTarget(int[][] matrix, int target) {
int ans = 0;
int m = matrix.length;
int n = matrix[0].length;
int[][] sum = new int[m + 1][n + 1];
Map<Integer, Integer> count = new HashMap<>();
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
sum[i][j] = sum[i][j - 1] + matrix[i - 1][j - 1];
}
}
int endY = 1;
while (endY <= n) {
for (int startY = 0; startY < endY; startY++) {
int now = 0;
count.clear();
count.put(0, 1);
for (int i = 1; i <= m; i++) {
now += sum[i][endY] - sum[i][startY];
if (count.containsKey(now - target)) {
ans += count.get(now - target);
}
count.put(now, count.getOrDefault(now, 0) + 1);
}
}
endY++;
}
return ans;
}