leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

1074.cpp (800B)


      1 class Solution {
      2   public:
      3     int numSubmatrixSumTarget(vector<vector<int>> &matrix, int target) const {
      4         const int n = size(matrix), m = size(matrix[0]);
      5 
      6         for (int i = 0; i < n; i++) {
      7             for (int j = 0, acc = 0; j < m; j++) {
      8                 matrix[i][j] = acc += matrix[i][j];
      9             }
     10         }
     11 
     12         unordered_map<int, int> um;
     13         int res = 0;
     14 
     15         for (int i = 0; i < m; i++) {
     16             for (int j = i; j < m; j++) {
     17                 um = {{0, 1}};
     18                 int crnt = 0;
     19                 for (int k = 0; k < n; k++) {
     20                     crnt += matrix[k][j] - (i > 0 ? matrix[k][i - 1] : 0);
     21                     res += um[crnt - target];
     22                     um[crnt]++;
     23                 }
     24             }
     25         }
     26 
     27         return res;
     28     }
     29 };