classNumMatrix { int[][] dp; int ylen; int xlen; publicNumMatrix(int[][] matrix) { ylen = matrix.length; xlen = matrix[0].length; dp = newint[ylen][xlen]; for (inty=0;y<ylen;y++) { intsum=0; for (intx=0; x < xlen; x++) { sum += matrix[y][x]; dp[y][x] = sum + (y-1>=0?dp[y-1][x]:0); } } } publicintsumRegion(int row1, int col1, int row2, int col2) { return sum(row2, col2) - sum(row2, col1-1) - sum(row1-1, col2) + sum(row1-1, col1-1); }
intsum(int y, int x) { if (y <0 || x < 0) { return0; } return dp[y][x]; } }
/** * Your NumMatrix object will be instantiated and called as such: * NumMatrix obj = new NumMatrix(matrix); * int param_1 = obj.sumRegion(row1,col1,row2,col2); */