|
98 | 98 |
|
99 | 99 | <!-- solution:start --> |
100 | 100 |
|
101 | | -### Solution 1 |
| 101 | +### Solution 1: Memoized Search |
| 102 | + |
| 103 | +We design a function $\textit{dfs}(i, \textit{cur}, t)$ that represents the maximum number of partitions we can obtain when currently processing index $i$ of string $s$, the current prefix already contains the character set $\textit{cur}$, and we can still modify $t$ characters. Then the answer is $\textit{dfs}(0, 0, 1)$. |
| 104 | + |
| 105 | +The execution logic of function $\textit{dfs}(i, \textit{cur}, t)$ is as follows: |
| 106 | + |
| 107 | +1. If $i \geq n$, it means we have finished processing string $s$, return 1. |
| 108 | +2. Calculate the bitmask $v = 1 \ll (s[i] - 'a')$ corresponding to the current character $s[i]$, and calculate the updated character set $\textit{nxt} = \textit{cur} \mid v$. |
| 109 | +3. If the number of bits in $\textit{nxt}$ exceeds $k$, it means the current prefix already contains more than $k$ distinct characters. We need to make a partition, increment the partition count by 1, and recursively call $\textit{dfs}(i + 1, v, t)$. Otherwise, continue recursively calling $\textit{dfs}(i + 1, \textit{nxt}, t)$. |
| 110 | +4. If $t > 0$, it means we can still modify a character once. We try to change the current character $s[i]$ to any lowercase letter (26 choices in total). For each choice, calculate the updated character set $\textit{nxt} = \textit{cur} \mid (1 \ll j)$, and based on whether it exceeds $k$ distinct characters, choose the corresponding recursive call method to update the maximum partition count. |
| 111 | +5. Use a hash table to cache already computed states to avoid redundant calculations. |
| 112 | + |
| 113 | +The time complexity is $O(n \times |\Sigma| \times k)$ and the space complexity is $O(n \times |\Sigma| \times k)$, where $n$ is the length of string $s$, and $|\Sigma|$ is the size of the character set. |
102 | 114 |
|
103 | 115 | <!-- tabs:start --> |
104 | 116 |
|
@@ -179,7 +191,7 @@ public: |
179 | 191 | int maxPartitionsAfterOperations(string s, int k) { |
180 | 192 | int n = s.size(); |
181 | 193 | unordered_map<long long, int> f; |
182 | | - function<int(int, int, int)> dfs = [&](int i, int cur, int t) { |
| 194 | + auto dfs = [&](this auto&& dfs, int i, int cur, int t) -> int { |
183 | 195 | if (i >= n) { |
184 | 196 | return 1; |
185 | 197 | } |
|
0 commit comments