Very similar to Range Sum Query - Immutable, but we now need to compute a 2d accunulated-sum. In fact, if you work in computer vision, you may know a name for such an array --- Integral Image.

To solve this problem, Stefan has already posted a very elegant solution.

The code is copied here.

 class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) {
accu = matrix;
for (int i = ; i < matrix.size(); i++)
for (int j = ; j < matrix[].size(); j++)
accu[i][j] += a(i-, j) + a(i, j-) - a(i-, j-);
} int sumRegion(int row1, int col1, int row2, int col2) {
return a(row2, col2) - a(row1-, col2) - a(row2, col1-) + a(row1-, col1-);
}
private:
vector<vector<int>> accu;
int a(int i, int j) {
return i >= && j >= ? accu[i][j] : ;
}
}; // Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);
05-03 22:44