# 308. Range Sum Query 2D - Mutable

**<font color=red>难度: Hard</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/range-sum-query-2d-mutable/

> 内容描述

```
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
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10
Note:
The matrix is only modifiable by the update function.
You may assume the number of calls to update and sumRegion function is distributed evenly.
You may assume that row1 ≤ row2 and col1 ≤ col2.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(col) + O(row)******- 空间复杂度: O(row * col)******



无非就是前缀和, beats 66.04%

时间复杂度：
1. update: O(col)
2. sumRegion: O(row)


```python
class NumMatrix(object):

    def __init__(self, matrix):
        """
        :type matrix: List[List[int]]
        """
        self.row = len(matrix)
        self.col = len(matrix[0]) if self.row else 0
        self.prefixs = []
        for i in range(self.row):
            prefix = [0] * (self.col + 1)
            for j in range(1, self.col+1):
                prefix[j] = prefix[j-1] + matrix[i][j-1]
            self.prefixs.append(prefix)

    def update(self, row, col, val):
        """
        :type row: int
        :type col: int
        :type val: int
        :rtype: void
        """
        change = self.prefixs[row][col+1] - self.prefixs[row][col]
        for j in range(col+1, self.col+1):
            self.prefixs[row][j] += val - change

    def sumRegion(self, row1, col1, row2, col2):
        """
        :type row1: int
        :type col1: int
        :type row2: int
        :type col2: int
        :rtype: int
        """
        res = 0
        for i in range(row1, row2+1):
            res += self.prefixs[i][col2+1] - self.prefixs[i][col1]
        return res
```































