File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ # -*- coding: utf-8 -*-
2+
3+ class Solution :
4+ # @param {int[][]} matrix an integer matrix
5+ # @return {int[][]} the coordinate of the left-up and right-down number
6+ def submatrixSum (self , matrix ):
7+ # Write your code here
8+ '''
9+ O(n ^ 4)的做法太多了,就不多讨论了。
10+ 1. 原始矩阵如下:
11+ [1, 5, 7]
12+ [3, 7, -8]
13+ [4, -8, 9]
14+ 2. 构造扩展矩阵,令s[i][j]为m[0][0]到m[i - 1][j - 1]的子矩阵和。(闭区间)
15+ [0, 0, 0, 0]
16+ [0, 1, 6, 13]
17+ [0, 4, 16, 15]
18+ [0, 8, 12, 20]
19+ 3. i2 >= i1, s[i2][k] - s[i1][k]的差等于m[i1][0]到m[i2 - 1][k - 1]的子矩阵的和。(闭区间)
20+ 以s[2][2] - s[1][2] = 16 - 6 = 10。m[1][0]到m[2][1]
21+ 4. 继续不在3,如果s[i2][j] - s[i1][j]等于s[i2][k] - s[i1][k],
22+ 那么说明m[i1][k]到m[i2 - 1][j - 1]的子矩阵和为0
23+ '''
24+ rows = len (matrix )
25+ cols = len (matrix [0 ])
26+ sums = [[0 ] * (cols + 1 ) for i in xrange (rows + 1 )]
27+ for i in xrange (rows ):
28+ for j in xrange (cols ):
29+ sums [i + 1 ][j + 1 ] = matrix [i ][j ] + sums [i + 1 ][j ] + sums [i ][j + 1 ] - sums [i ][j ]
30+ ret = [[None , None ], [None , None ]]
31+ for i in xrange (rows ):
32+ for j in xrange (i + 1 , rows + 1 ):
33+ cache = {}
34+ for k in xrange (cols + 1 ):
35+ sub_sum = sums [j ][k ] - sums [i ][k ]
36+ if sub_sum in cache :
37+ ret [0 ][0 ] = i
38+ ret [0 ][1 ] = cache [sub_sum ]
39+ ret [1 ][0 ] = j - 1
40+ ret [1 ][1 ] = k - 1
41+ return ret
42+ cache [sub_sum ] = k
43+ return ret
You can’t perform that action at this time.
0 commit comments