forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
31 lines (31 loc) · 1.02 KB
/
Solution.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
class Solution {
public:
int maxPartitionsAfterOperations(string s, int k) {
int n = s.size();
unordered_map<long long, int> f;
function<int(int, int, int)> dfs = [&](int i, int cur, int t) {
if (i >= n) {
return 1;
}
long long key = (long long) i << 32 | cur << 1 | t;
if (f.count(key)) {
return f[key];
}
int v = 1 << (s[i] - 'a');
int nxt = cur | v;
int ans = __builtin_popcount(nxt) > k ? dfs(i + 1, v, t) + 1 : dfs(i + 1, nxt, t);
if (t) {
for (int j = 0; j < 26; ++j) {
nxt = cur | (1 << j);
if (__builtin_popcount(nxt) > k) {
ans = max(ans, dfs(i + 1, 1 << j, 0) + 1);
} else {
ans = max(ans, dfs(i + 1, nxt, 0));
}
}
}
return f[key] = ans;
};
return dfs(0, 0, 1);
}
};