题目:
强烈建议这道题归入简单题(手动狗头.jpg)
昨天的题目就是今天这题的解法,只需要新建一个矩阵存储每一行的前缀和,最后要哪几行几列之间,和昨天相同计算就好了。
C++代码附带测试:
#include<iostream>
#include<vector>
using namespace std;
class NumMatrix {
public:
vector<vector<int>> a;
NumMatrix(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
if(m>0)
{
a.resize(m, vector<int>(n + 1));
for(int i = 0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j+1] = a[i][j] + matrix[i][j];
}
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
int sum = 0;
for(int n = row1;n<=row2;n++)
{
sum = sum + a[n][col2+1] -a[n][col1];
}
return sum;
}
};
int main()
{
vector<vector<int>> matrix = {{3, 0, 1, 4, 2},{5, 6, 3, 2, 1},{1, 2, 0, 1, 5},{4, 1, 0, 1, 7},{1, 0, 3, 0, 5}};
NumMatrix nmatrix = NumMatrix(matrix);
int sum = nmatrix.sumRegion(2,1,4,3);
cout<<sum;
}