zoukankan      html  css  js  c++  java
  • 304. Range Sum Query 2D

    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  */
     
  • 相关阅读:
    硬件的效率与一致性
    深入理解SPI机制-服务发现机制
    spring 之7种重要设计模式
    list里放map list 放list
    jvm 三种编译
    几种不同格式的json解析
    Java知识点梳理——集合
    判断2个list中是否有相同的数据(相交)Collections.disjoint
    键相同,比较两个map中的值是否相同
    Map类型数据导出Excel--poi
  • 原文地址:https://www.cnblogs.com/zle1992/p/10466694.html
Copyright © 2011-2022 走看看