cpp: add «1074. Number of Submatrices That Sum to Target»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
2c3f0e2255
commit
3f7519022a
1 changed files with 55 additions and 0 deletions
55
cpp/number-of-submatrices-that-sum-to-target.cpp
Normal file
55
cpp/number-of-submatrices-that-sum-to-target.cpp
Normal file
|
@ -0,0 +1,55 @@
|
|||
#include <cassert>
|
||||
#include <vector>
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
auto numSubmatrixSumTarget(const std::vector<std::vector<int>> &matrix,
|
||||
int target) -> int {
|
||||
int rows = matrix.size();
|
||||
int cols = matrix[0].size();
|
||||
|
||||
int count = 0;
|
||||
for (int l = 0; l < cols; ++l) {
|
||||
std::vector<int> sums(rows, 0);
|
||||
|
||||
for (int r = l; r < cols; ++r) {
|
||||
for (int i = 0; i < rows; ++i) {
|
||||
sums[i] += matrix[i][r];
|
||||
}
|
||||
|
||||
for (int i = 0; i < rows; ++i) {
|
||||
int sum = 0;
|
||||
|
||||
for (int j = i; j < rows; ++j) {
|
||||
sum += sums[j];
|
||||
|
||||
if (sum == target) {
|
||||
++count;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
Solution s;
|
||||
|
||||
assert(s.numSubmatrixSumTarget(std::vector{std::vector{0, 1, 0},
|
||||
std::vector{1, 1, 1},
|
||||
std::vector{0, 1, 0}},
|
||||
0) == 4);
|
||||
assert(s.numSubmatrixSumTarget(
|
||||
std::vector{std::vector{1, -1}, std::vector{-1, 1}}, 0) == 5);
|
||||
|
||||
assert(s.numSubmatrixSumTarget(
|
||||
std::vector<std::vector<int>>{
|
||||
std::vector{904},
|
||||
},
|
||||
0) == 0);
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in a new issue