官方题解
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <unordered_map>
#define _for(i, a, b) for (int i = a; i < b; i++)
using namespace std;
int subarraySum(vector<int> &nums, int k)
{
cout<<endl;
unordered_map<int, int> mp;
mp[0] = 1;
int count = 0, pre = 0;
for (auto &x : nums)
{
cout<<"key="<<pre<<" value="<<mp[pre]<<endl;
pre += x;
if (mp.find(pre - k) != mp.end())
{
count += mp[pre - k];
cout<<"count="<<count<<endl;
}
mp[pre]++;
}
cout<<"key="<<pre<<" value="<<mp[pre]<<endl;
return count;
}
int numSubmatrixSumTarget(vector<vector<int>> &matrix, int target)
{
int ans = 0;
int m = matrix.size(), n = matrix[0].size();
for (int i = 0; i < m; ++i)
{ // 枚举上边界
vector<int> sum(n);
for (int j = i; j < m; ++j)
{ // 枚举下边界
for (int c = 0; c < n; ++c)
{
sum[c] += matrix[j][c]; // 更新每列的元素和
cout<<sum[c];
}
ans += subarraySum(sum, target);
cout<<endl;
}
}
return ans;
}
//
int main()
{
freopen("D:\\zx.txt", "r", stdin);
int hang = 5;
int lie = 5;
vector<vector<int>> v(hang, vector<int>(lie));
for (int i = 0; i < hang; i++)
{
for (int j = 0; j < lie; j++)
{
cin >> v[i][j];
}
}
cout << numSubmatrixSumTarget(v, 0);
system("pause");
return 0;
}