Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
number-of-submatrices-that-sum-to-target.py 1.06 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2019-06-02 20:32 +08:00 . Create number-of-submatrices-that-sum-to-target.py
# Time: O(m^2*n), m is min(r, c), n is max(r, c)
# Space: O(n), which doesn't include transposed space
import collections
class Solution(object):
def numSubmatrixSumTarget(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: int
"""
if len(matrix) > len(matrix[0]):
return self.numSubmatrixSumTarget(map(list, zip(*matrix)), target)
for i in xrange(len(matrix)):
for j in xrange(len(matrix[i])-1):
matrix[i][j+1] += matrix[i][j]
result = 0
for i in xrange(len(matrix)):
prefix_sum = [0]*len(matrix[i])
for j in xrange(i, len(matrix)):
lookup = collections.defaultdict(int)
lookup[0] = 1
for k in xrange(len(matrix[j])):
prefix_sum[k] += matrix[j][k]
if prefix_sum[k]-target in lookup:
result += lookup[prefix_sum[k]-target]
lookup[prefix_sum[k]] += 1
return result
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助