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; }
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; } }
|