-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path304.二维区域和检索-矩阵不可变.cpp
41 lines (35 loc) · 974 Bytes
/
304.二维区域和检索-矩阵不可变.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
* @lc app=leetcode.cn id=304 lang=cpp
*
* [304] 二维区域和检索 - 矩阵不可变
*/
// @lc code=start
#include<iostream>
#include<vector>
using namespace std;
class NumMatrix {
public:
vector<vector<int>> dp;
NumMatrix(vector<vector<int>>& matrix) {
int m = matrix.size();
if(m==0)return;
int n = matrix[0].size();
dp = vector<vector<int>>(m+1, vector<int>(n+1, 0));
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
dp[i+1][j+1] = dp[i+1][j]+ dp[i][j+1] + matrix[i][j] - dp[i][j];
}
}
}
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];
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
*/
// @lc code=end