-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
number-of-good-binary-strings.cpp
55 lines (51 loc) · 1.65 KB
/
number-of-good-binary-strings.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
// Time: O(n), n = maxLength
// Space: O(w), w = max(oneGroup, zeroGroup)+1
// dp
class Solution {
public:
int goodBinaryStrings(int minLength, int maxLength, int oneGroup, int zeroGroup) {
static const int MOD = 1e9 + 7;
int result = 0;
const int w = max(oneGroup, zeroGroup) + 1;
vector<int> dp(w);
for (int i = 0; i <= maxLength; ++i) {
dp[i % w] = i == 0 ? 1 : 0;
if (i - oneGroup >= 0) {
dp[i % w] = (dp[i % w] + dp[(i - oneGroup) % w]) % MOD;
}
if (i - zeroGroup >= 0 ) {
dp[i % w] = (dp[i % w] + dp[(i - zeroGroup) % w]) % MOD;
}
if (i >= minLength) {
result = (result + dp[i % w]) % MOD;
}
}
return result;
}
};
// Time: O(n), n = maxLength
// Space: O(w), w = max(oneGroup, zeroGroup)+1
// dp
class Solution2 {
public:
int goodBinaryStrings(int minLength, int maxLength, int oneGroup, int zeroGroup) {
static const int MOD = 1e9 + 7;
int result = 0;
const int w = max(oneGroup, zeroGroup) + 1;
vector<int> dp(w);
dp[0] = 1;
for (int i = 0; i <= maxLength; ++i) {
if (i >= minLength) {
result = (result + dp[i % w]) % MOD;
}
if (i + oneGroup <= maxLength) {
dp[(i + oneGroup) % w] = (dp[(i + oneGroup) % w] + dp[i % w]) % MOD;
}
if (i + zeroGroup <= maxLength) {
dp[(i + zeroGroup) % w] = (dp[(i + zeroGroup) % w] + dp[i % w]) % MOD;
}
dp[i % w] = 0;
}
return result;
}
};