Skip to content

Commit eb56c42

Browse files
Update Solution.py
Invalid Syntax error Removed
1 parent c735017 commit eb56c42

File tree

1 file changed

+30
-19
lines changed
  • solution/1000-1099/1074.Number of Submatrices That Sum to Target

1 file changed

+30
-19
lines changed
Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,32 @@
11
class Solution:
2-
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
3-
def f(nums: List[int]) -> int:
4-
d = defaultdict(int)
5-
d[0] = 1
6-
cnt = s = 0
7-
for x in nums:
8-
s += x
9-
cnt += d[s - target]
10-
d[s] += 1
11-
return cnt
2+
def numSubmatrixSumTarget(self, matrix, target):
3+
"""
4+
:type matrix: List[List[int]]
5+
:type target: int
6+
:rtype: int
7+
"""
8+
m = len(matrix)
9+
n = len(matrix[0])
10+
ans = 0
11+
for i in range(m):
12+
col = [0] * n
13+
for j in range(i, m):
14+
for k in range(n):
15+
col[k] += matrix[j][k]
16+
ans += self.f(col, target)
17+
return ans
1218

13-
m, n = len(matrix), len(matrix[0])
14-
ans = 0
15-
for i in range(m):
16-
col = [0] * n
17-
for j in range(i, m):
18-
for k in range(n):
19-
col[k] += matrix[j][k]
20-
ans += f(col)
21-
return ans
19+
def f(self, nums, target):
20+
"""
21+
:type nums: List[int]
22+
:type target: int
23+
:rtype: int
24+
"""
25+
d = {0: 1} # map to store prefix sum counts
26+
s = 0
27+
cnt = 0
28+
for x in nums:
29+
s += x
30+
cnt += d.get(s - target, 0) # count subarray sums equal to target
31+
d[s] = d.get(s, 0) + 1 # update prefix sum count
32+
return cnt

0 commit comments

Comments
 (0)