LC.P1074[元素和为目标值的子矩阵数量]

方法一:前缀和+哈希表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public int numSubmatrixSumTarget(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length, ans = 0;
// 枚举上边界
for (int i = 0; i < m; ++i) {
int[] sum = new int[n];
// 枚举下边界
for (int j = i; j < m; ++j) {
for (int k = 0; k < n; ++k) {
// 更新每列的元素和
sum[k] += matrix[j][k];
}
ans += subarraySum(sum, target);
}
}
return ans;
}

// LC.P569[和为K的子数组]
public int subarraySum(int[] nums, int k) {
int pre = 0, ans = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
for (int num : nums) {
pre += num;
if (map.containsKey(pre - k)) {
ans += map.get(pre - k);
}
map.merge(pre, 1, Integer::sum);
}
return ans;
}
}
  • 时间复杂度:$O(m^2n)$
  • 空间复杂度:$O(n)$