-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathcount-submatrices-with-all-ones.cpp
66 lines (62 loc) · 2.02 KB
/
count-submatrices-with-all-ones.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Time: O(m * n)
// Space: O(n)
// mono stack
class Solution {
public:
int numSubmat(vector<vector<int>>& mat) {
const auto& count = [](const auto& heights) {
int result = 0;
vector<int> stk;
for (int i = 0, curr = 0; i < size(heights); ++i) {
while (!empty(stk) && heights[stk.back()] >= heights[i]) {
const int j = stk.back(); stk.pop_back();
curr -= (heights[j] - heights[i]) * (j - (!empty(stk) ? stk.back() : -1));
}
stk.emplace_back(i);
curr += heights[i];
result += curr;
}
return result;
};
int result = 0;
vector<int> heights(size(mat[0]));
for (int i = 0; i < size(mat); ++i) {
for (int j = 0; j < size(mat[0]); ++j) {
heights[j] = (mat[i][j] == 1) ? heights[j] + 1 : 0;
}
result += count(heights);
}
return result;
}
};
// Time: O(m * n)
// Space: O(n)
// mono stack, dp
class Solution2 {
public:
int numSubmat(vector<vector<int>>& mat) {
const auto& count = [](const auto& heights) {
vector<int> dp(size(heights));
vector<int> stk;
for (int i = 0; i < size(heights); ++i) {
while (!empty(stk) && heights[stk.back()] >= heights[i]) {
stk.pop_back();
}
dp[i] = !empty(stk)
? dp[stk.back()] + heights[i] * (i - stk.back())
: heights[i] * (i - (-1));
stk.emplace_back(i);
}
return accumulate(cbegin(dp), cend(dp), 0);
};
int result = 0;
vector<int> heights(size(mat[0]));
for (int i = 0; i < size(mat); ++i) {
for (int j = 0; j < size(mat[0]); ++j) {
heights[j] = (mat[i][j] == 1) ? heights[j] + 1 : 0;
}
result += count(heights);
}
return result;
}
};