Skip to content

Commit

Permalink
Update 1074.Number-of-Submatrices-That-Sum-to-Target.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Apr 17, 2021
1 parent a53a040 commit 52faeea
Showing 1 changed file with 19 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,29 @@ class Solution {
public:
int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target)
{
int M = matrix.size();
int N = matrix[0].size();

int m = matrix.size(), n = matrix[0].size();
int count = 0;
for (int i=0; i<M; i++)

for (int i=0; i<m; i++)
{
vector<int>temp(N,0);
for (int j=i; j<M; j++)
vector<int>row(n);
for (int t=i; t<m; t++)
{
for (int k=0; k<N; k++)
temp[k] += matrix[j][k];
count += helper(temp,target);
}
}
return count;
}

int helper(vector<int>&nums, int target)
{
int N = nums.size();
int presum = 0;
unordered_map<int,int>presumMap;
presumMap[0] = 1;
int count = 0;
for (int j=0; j<N; j++)
{
presum += nums[j];
if (presumMap.find(presum - target)!=presumMap.end())
count+=presumMap[presum - target];
presumMap[presum]+=1;
for (int j=0; j<n; j++)
row[j] += matrix[t][j];

unordered_map<int,int>Map;
Map[0] = 1;
int presum = 0;
for (int j=0; j<n; j++)
{
presum += row[j];
count += Map[presum - target];
Map[presum]+=1;
}
}
}
return count;

}
};

0 comments on commit 52faeea

Please sign in to comment.