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.
Solution:can is simplified to add one column and one row to DP (Dp[row+1][column+1])
1 Public classNummatrix {2 Private int[,] DP {Get;Set;}3 PublicNummatrix (int[,] matrix) {4 intr = Matrix. GetLength (0);5 intc = Matrix. GetLength (1);6 if(r>0&&c>0)7 {8DP =New int[R, c];9 for(intI=0; i<r;i++)Ten { One for(intj=0;j<c; J + +) A { - if(i==0&&j==0) - { thedp[0,0]=matrix[0,0]; - } - Else if(i==0) - { +dp[0, j]=dp[0, J-1]+matrix[0, j]; - } + Else if(j==0) A { atDp[i,0] = dp[i-1,0]+matrix[i,0]; - } - Else - { -DP[I,J] = dp[i-1, J]+dp[i, J-1]-dp[i-1, J-1]+Matrix[i,j]; - } in } - } to } + - } the * Public intSumregion (intRow1,intCol1,intRow2,intcol2) { $ if(row1==0&& col1==0)Panax Notoginseng { - returnDp[row2,col2]; the } + Else if(col1==0) A { the returnDp[row2, col2]-dp[row1-1, col2]; + } - Else if(row1==0) $ { $ returnDp[row2, Col2]-dp[row2, col1-1]; - } - Else the { - returnDp[row2, col2]-dp[row1-1, Col2]-dp[row2, col1-1]+dp[row1-1, col1-1];Wuyi } the } -}
Leetcode 304. Range Sum Query 2d-immutable