From cb8b064302b3bb7dd453de79030ac2b418bac71e Mon Sep 17 00:00:00 2001 From: Jiajionline Date: Sun, 1 Oct 2023 09:46:31 -0700 Subject: [PATCH] Leetcode 1074 Number of Submatrices That Sum to Target --- .../NumberofSubmatricesThatSumtoTarget2.java | 46 +++++++++---------- 1 file changed, 21 insertions(+), 25 deletions(-) diff --git a/1074_Number of Submatrices That Sum to Target/NumberofSubmatricesThatSumtoTarget2.java b/1074_Number of Submatrices That Sum to Target/NumberofSubmatricesThatSumtoTarget2.java index 2a455e1..e21ee3c 100644 --- a/1074_Number of Submatrices That Sum to Target/NumberofSubmatricesThatSumtoTarget2.java +++ b/1074_Number of Submatrices That Sum to Target/NumberofSubmatricesThatSumtoTarget2.java @@ -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 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 map = new HashMap<>(); + map.put(0,1); + for(int col=1;col