304. Range Sum Query 2D - Immutable
Question
Given a 2D matrix
matrix
, handle multiple queries of the following type:
- Calculate the sum of the elements of
matrix
inside the rectangle defined by its upper left corner(row1, col1)
and lower right corner(row2, col2)
.Implement the NumMatrix class:
NumMatrix(int[][] matrix)
Initializes the object with the integer matrixmatrix
.int sumRegion(int row1, int col1, int row2, int col2)
Returns the sum of the elements ofmatrix
inside the rectangle defined by its upper left corner(row1, col1)
and lower right corner(row2, col2)
.
Solution
前缀和/动态规划,用一个dp[][]数组记录到matrix[0][0]到matrix[i][j]区域的和。
计算两个点之间形成的总数只需用外侧的位置的前缀和加上内侧位置的前缀和,然后减去两者交换长宽位置的前缀和即可。
递推公式
计算dp[][]数组时,需要将其上侧与左侧所有数字加和,并加上matrix[][]上该位置对应的元素。
用dp[i][j-1] - dp[i-1][j-1]计算出左侧所有数字之和,dp[i-1][j]则是上侧所有数字之和。
Code
1 | class NumMatrix { |
Solution 2
暴力搜索,直接计算从row1, col1到row2, col2的元素加和。
Code
1 | class NumMatrix { |
304. Range Sum Query 2D - Immutable
https://xuanhe95.github.io/2022/06/03/304-Range-Sum-Query-2D-Immutable/