-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbeautifulPartitions.cpp
More file actions
36 lines (32 loc) · 1.33 KB
/
beautifulPartitions.cpp
File metadata and controls
36 lines (32 loc) · 1.33 KB
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
class Solution {
static constexpr int MOD = 1e9 + 7;
bool is_prime(char c) {
return c == '2' || c == '3' || c == '5' || c == '7';
}
// 判断是否可以在 j-1 和 j 之间分割(开头和末尾也算)
bool can_partition(string &s, int j) {
return j == 0 || j == s.length() || !is_prime(s[j - 1]) && is_prime(s[j]);
}
public:
int beautifulPartitions(string &s, int k, int l) {
int n = s.length();
if (k * l > n || !is_prime(s[0]) || is_prime(s[n - 1]))
return 0;
int f[k + 1][n + 1];
memset(f, 0, sizeof(f));
f[0][0] = 1;
for (int i = 1; i <= k; ++i) {
int sum = 0;
// 优化:枚举的起点和终点需要给前后的子串预留出足够的长度
for (int j = i * l; j + (k - i) * l <= n; j++) {
if (can_partition(s, j - l)) sum = (sum + f[i - 1][j - l]) % MOD; // j'=j-l 双指针
if (can_partition(s, j)) f[i][j] = sum;
}
}
return f[k][n];
}
};
// 作者:灵茶山艾府
// 链接:https://leetcode.cn/problems/number-of-beautiful-partitions/solutions/1981346/dong-tai-gui-hua-jian-ji-xie-fa-xun-huan-xyw3/
// 来源:力扣(LeetCode)
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。