Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by it upper left corner ( row1, Col1) and lower right corner ( row2, Col2).
The above rectangle (with the red border) are defined by (row1, col1) = (2, 1) and (Row2, col2) = (4, 3), which contains Su m = 8.
Example:
Given 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]] Sumregion (2, 1, 4, 3), 8sumRegion (1, 1, 2, 2), 11sumRegion (1, 2, 2, 4), 12
Note:
- Assume that the matrix does not a change.
- There is many calls to sumregion function.
- Assume that row1≤ row2 and Col1≤ Col2.
Exercises
The two-dimensional situation is similar to one-dimensional thinking, which is to ask for a recursive type and then put and preprocess it, then O (1) query.
One-dimensional recursion is: s[i]=s[i-1]+a[i];
Two-dimensional by drawing: s[i][j]=a[i][j]+s[i-1][j]+s[i][j-1]-s[i-1][j-1];
classNummatrix { Public: Nummatrix (Vector<vector<int>> &matrix) {N=matrix.size (); M=n>0? matrix[0].size ():0; S=vector<vector<int>> (n+1,vector<int> (m+1,0)); for(intI=1; i<=n;i++){ for(intj=1; j<=m;j++) {S[i][j]=matrix[i-1][j-1]+s[i-1][j]+s[i][j-1]-s[i-1][j-1]; } } } intSumregion (intRow1,intCol1,intRow2,intcol2) { returns[row2+1][col2+1]-s[row2+1][col1]-s[row1][col2+1]+S[row1][col1]; }Private: intn,m; Vector<vector<int> >s;};//Your Nummatrix object would be instantiated and called as such://Nummatrix Nummatrix (matrix);//nummatrix.sumregion (0, 1, 2, 3);//nummatrix.sumregion (1, 2, 3, 4);
Leetcode 304. Range Sum Query 2d-immutable (Recursive)