Submatrices Sum.
// CY first attempt (5728 ms, 48.58%, 13 MB, 100%) int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) { const int m = matrix.size(), n = matrix[0].size(); vector<int> prefSum(m + 1); vector<int> rowSum(m); int total = 0; for (int i = 0; i < n; ++i) { fill(rowSum.begin(), rowSum.end(), 0); for (int j = i; j < n; ++j) { for (int k = 0; k < m; ++k) rowSum[k] += matrix[k][j]; for (int k = 1; k <= m; ++k) prefSum[k] = prefSum[k - 1] + rowSum[k - 1]; for (int k1 = 0; k1 < m; ++k1) for (int k2 = k1 + 1; k2 <= m; ++k2) if (prefSum[k2] - prefSum[k1] == target) ++total; } } return total; }
No comments:
Post a Comment