題目如下:
Given a
matrix
, and atarget
, return the number of non-empty submatrices that sum to target.A submatrix
x1, y1, x2, y2
is the set of all cellsmatrix[x][y]
withx1 <= x <= x2
andy1 <= y <= y2
.Two submatrices
(x1, y1, x2, y2)
and(x1', y1', x2', y2')
are different if they have some coordinate that is different: for example, ifx1 != x1'
.
Example 1:
Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 Output: 4 Explanation: The four 1x1 submatrices that only contain 0.
Example 2:
Input: matrix = [[1,-1],[-1,1]], target = 0 Output: 5 Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
Note:
1 <= matrix.length <= 300
1 <= matrix[0].length <= 300
-1000 <= matrix[i] <= 1000
-10^8 <= target <= 10^8
解題思路:暴力計算的方法時間復雜度是O(n^4),而matrix.length最大值是300,應該無法被AC。那O(n^3)可以嗎?試試吧。首先引入一個二維數組val_grid , 記var_grid[m][n] 為從0開始到第m行這個區間內第n列的值的和,例如用例1中的輸入[[0,1,0],[1,1,1],[0,1,0]],其對應的val_grid為[[0, 1, 0], [1, 2, 1], [1, 3, 1]] 。如果要計算matrix中第j行~第i行區間內有多少滿足和等於target的子矩陣,很輕松就可以求出這個子矩陣每一列的和,例如第k的列的和為 val_grid[i][k] - val_grid[j-1][k] (j>0),接下來令k in range(0,len(matrix[0]),依次判斷[j~i]每一列的和是否等於target,同時累加並記錄從0開始的列和,假設[0~k]累計的列和是sum,只要判斷歷史的列和中有多少個滿足 sum - target,即可求出[j~i]子矩陣里面以k列為右邊列的滿足條件的子矩陣個數。這樣即可將復雜度優化成O(n^3)。
代碼如下:
class Solution(object): def numSubmatrixSumTarget(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: int """ val_grid = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))] for j in range(len(matrix[0])): amount = 0 for i in range(len(matrix)): amount += matrix[i][j] val_grid[i][j] = amount #print val_grid res = 0 for i in range(len(matrix)): for j in range(i+1): dic = {} amount = 0 for k in range(len(matrix[i])): v = val_grid[i][k] if j > 0: v -= val_grid[j-1][k] amount += v if amount == target:res += 1 if amount - target in dic: res += dic[amount - target] dic[amount] = dic.setdefault(amount,0) + 1 return res