Question Link
https://leetcode.com/problems/range-sum-query-2d-immutable/
Question Description
Given a 2D matrix matrix, and compute the range sum of row and columns 
Input [“NumMatrix”, “sumRegion”, “sumRegion”, “sumRegion”] [[[[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]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]
Output [null, 8, 11, 12]
Simulation
Solution 1: Brutal
Solution 2:DP + Prefix Sum
Use DP to compute below array
dp[r + 1][c + 1] = dp[r + 1][c] + dp[r][c + 1] + matrix[r][c] - dp[r][c]
Calculate the sum based on below formula



Sum(ABCD)=Sum(OD)−Sum(OB)−Sum(OC)+Sum(OA)
Implementation
Solution 1: Brutal Force
class NumMatrix {int [][] matrix;public NumMatrix(int[][] matrix) {this.matrix = matrix;}public int sumRegion(int row1, int col1, int row2, int col2) {int sum = 0;for (int i=row1;i<=row2;i++) {for (int j=col1;j<=col2;j++) {sum+=matrix[i][j];}}return sum;}}
Solution 2: DP + Prefix Sum
public class NumMatrix {private int[][] dp;public NumMatrix(int[][] matrix) {if (matrix.length == 0 || matrix[0].length == 0) return;dp = new int[matrix.length + 1][matrix[0].length + 1];for (int r = 0; r < matrix.length; r++) {for (int c = 0; c < matrix[0].length; c++) {dp[r + 1][c + 1] = dp[r + 1][c] + dp[r][c + 1] + matrix[r][c] - dp[r][c];}}}public int sumRegion(int row1, int col1, int row2, int col2) {return dp[row2 + 1][col2 + 1] - dp[row1][col2 + 1] - dp[row2 + 1][col1] + dp[row1][col1];}}
