-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
count-the-number-of-winning-sequences.cpp
42 lines (40 loc) · 1.25 KB
/
count-the-number-of-winning-sequences.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
// Time: O(n^2)
// Space: O(n)
// dp
class Solution {
public:
int countWinningSequences(string s) {
static const int MOD = 1e9 + 7;
static const unordered_map<char, int> lookup = {{'F', 0}, {'W', 1}, {'E', 2}};
vector<unordered_map<int, int>> dp(3);
for (int i = 0; i < size(s); ++i) {
vector<unordered_map<int, int>> new_dp(3);
const auto x = lookup.at(s[i]);
for (int j = 0; j < 3; ++j) {
const int diff = ((j - x + 1) % 3 + 3) % 3 - 1;
if (i == 0) {
new_dp[j][diff] = 1;
continue;
}
for (int k = 0; k < 3; ++k) {
if (k == j) {
continue;
}
for (const auto& [v, c] : dp[k]) {
new_dp[j][v + diff] = (new_dp[j][v + diff] + c) % MOD;
}
}
}
dp = move(new_dp);
}
int result = 0;
for (int j = 0; j < 3; ++j) {
for (const auto& [v, c] : dp[j]) {
if (v >= 1) {
result = (result + c) % MOD;
}
}
}
return result;
}
};