3,031-D version of the array, the method is to use a two-dimensional array of res deposit from (0,0) to the current position of sum, the method is dynamic programming, look at the two-dimensional array circle is better to understand the addition and subtraction
The sum of the operator array is also the same as the logic of the existence, that is, a part plus another part, and then subtract a part of the logical drawing circle can be seen
The importance of comparison is the dynamic planning of the process of storage, the next two-dimensional array problems should be used frequently
Packagecom. dynamicprogramming;ImportJava.util.HashMap;ImportJava.util.Map;/*** Given a 2D matrix matrix, * Find the sum of the elements inside the rectangle defined by it upper left corner (row 1, col1) and lower right corner (Row2, col2). * 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]] Sumregio N (2, 1, 4, 3)-8 sumregion (1, 1, 2, 2)-sumregion (1, 2, 2, 4), note:you may assume the matrix D OES not a change. There is many calls to Sumregion function. Assume that Row1≤row2 and col1≤col2. */ Public classq304rangesumquery2d_immutable {/*** Your Nummatrix object would be instantiated and called as such: * Nummatrix obj = new Nummatrix (matrix); * int param_1 = obj.sumregion (row1,col1,row2,col2); */ classNummatrix {int[] data; PublicNummatrix (int[] matrix) { if(Matrix.length = = 0) return; intm =matrix.length; intn = matrix[0].length; Data=New int[M][n]; //Initial conditions 1Data[0][0] = matrix[0][0]; //initial Condition 2, also dynamic planning 1 for(inti = 1; I < m; i++) {data[i][0] = data[i-1][0] + matrix[i][0]; } for(inti = 1; I < n; i++) {data[0][i] = data[0][i-1] + matrix[0][i]; } //record sum from current location to (0,0) point, dynamic planning 2 for(inti = 1; I < m; i++) { for(intj = 1; J < N; J + +) {Data[i][j]= Data[i-1][j] + data[i][j-1]-data[i-1][j-1] +Matrix[i][j]; } } } Public intSumregion (intRow1,intCol1,intRow2,intcol2) { intres =Data[row2][col2]; if(col1 >= 1 && row1 >= 1) {res= Res-data[row2][col1-1]-data[row1-1][col2] + data[row1-1][col1-1]; } Else if(col1 >= 1) Res-= Data[row2][col1-1]; Else if(Row1 >= 1) Res-= Data[row1-1][col2]; returnRes; } }}
[Leetcode]304range sum Query 2d-immutable dynamic programming computes Sum of a two-dimensional array of neutrons