@@ -1134,6 +1134,34 @@ func (this *NumArray) SumRange(i int, j int) int {
1134
1134
1135
1135
<!-- tabs:end -->
1136
1136
1137
+ ## 304. 二维区域和检索 - 矩阵不可变
1138
+
1139
+ [ 原题链接] ( https://leetcode-cn.com/problems/range-sum-query-2d-immutable/ )
1140
+
1141
+ ### 解法一:二维前缀和
1142
+
1143
+ ``` python
1144
+ class NumMatrix :
1145
+
1146
+ def __init__ (self , matrix : List[List[int ]]):
1147
+ m = len (matrix)
1148
+ n = len (matrix[0 ]) if matrix else 0
1149
+ self .sums = [[0 for _ in range (n + 1 )] for _ in range (m + 1 )]
1150
+
1151
+ for i in range (m):
1152
+ for j in range (n):
1153
+ self .sums[i + 1 ][j + 1 ] = self .sums[i][j + 1 ] + self .sums[i + 1 ][j] - self .sums[i][j] + matrix[i][j]
1154
+
1155
+
1156
+ def sumRegion (self , row1 : int , col1 : int , row2 : int , col2 : int ) -> int :
1157
+ return self .sums[row2 + 1 ][col2 + 1 ] - self .sums[row2 + 1 ][col1] - self .sums[row1][col2 + 1 ] + self .sums[row1][col1]
1158
+
1159
+
1160
+ # Your NumMatrix object will be instantiated and called as such:
1161
+ # obj = NumMatrix(matrix)
1162
+ # param_1 = obj.sumRegion(row1,col1,row2,col2)
1163
+ ```
1164
+
1137
1165
## 309. 最佳买卖股票时机含冷冻期
1138
1166
1139
1167
[ 原题链接] ( https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ )
0 commit comments