304. Range Sum Query 2D - Immutable(动态规划)

Given a 2D matrix  matrix, find the sum of the elements inside the rectangle defined by its upper left corner ( row1,  col1) and lower right corner ( row2,  col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 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) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12

Note:

  1. You may assume that the matrix does not change.
  2. There are many calls to sumRegion function.
  3. You may assume that row1 ≤ row2 and col1 ≤ col2.

 

Sum(ABCD)=Sum(OD)Sum(OB)Sum(OC)+Sum(OA)

 ps: 注意dp的递推公式

 1 class NumMatrix {
 2 public:
 3     vector<vector<int>> dp;
 4     
 5     NumMatrix(vector<vector<int>> matrix) {
 6         int n =matrix.size();
 7         int m = n==0?0:matrix[0].size();
 8         
 9         
10         dp = vector<vector<int>>(n+1,vector<int>(m+1,0));
11         for(int i = 0 ;i<n;i++)
12             for(int j = 0;j<m;j++){
13                 dp[i+1][j+1] = dp[i][j+1]+dp[i+1][j]-dp[i][j]+matrix[i][j];
14             }
15     }
16     
17     int sumRegion(int rows1, int cols1, int rows2, int cols2) {
18         return dp[rows2+1][cols2+1] - dp[rows1][cols2+1] - dp[rows2+1][cols1] +dp[rows1][cols1];
19     }
20 };
21 
22 /**
23  * Your NumMatrix object will be instantiated and called as such:
24  * NumMatrix obj = new NumMatrix(matrix);
25  * int param_1 = obj.sumRegion(row1,col1,row2,col2);
26  */
 

猜你喜欢

转载自www.cnblogs.com/zle1992/p/10466694.html