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
| class NumMatrix { public: vector<vector<int>> sums; NumMatrix(vector<vector<int>>& matrix) {
int m = matrix.size(); if(m>0) { int n=matrix[0].size(); sums.resize(m+1, vector<int>(n + 1)); for (int i = 0; i < m; i++) for(int j = 0;j < n; j++) sums[i+1][j+1]=matrix[i][j]+sums[i][j+1]; } } int sumRegion(int row1, int col1, int row2, int col2) { int s=0; for(int k=col1+1;k<=col2+1;k++) { s+=sums[row2+1][k]-sums[row1][k]; } return s; } };
|