Skip to content

Commit aa57192

Browse files
committed
https://leetcode.cn/problems/number-of-beautiful-partitions
1 parent 79d7050 commit aa57192

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ Step 2. Add the dependency
4545

4646
<summary>展开查看</summary>
4747

48+
https://leetcode.cn/problems/number-of-beautiful-partitions
49+
4850
https://leetcode.cn/problems/minimum-fuel-cost-to-report-to-the-capital
4951

5052
https://leetcode.cn/problems/closest-nodes-queries-in-a-binary-search-tree
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
function beautifulPartitions(s: string, k: number, minLength: number): number {
2+
const MOD = 1e9 + 7;
3+
const l = minLength;
4+
5+
const n = s.length;
6+
if (k * l > n || !isPrime(s[0]) || isPrime(s[n - 1])) {
7+
// 剪枝
8+
return 0;
9+
}
10+
const f = Array(k + 1)
11+
.fill(0)
12+
.map(() => Array<number>(n + 1).fill(0));
13+
f[0][0] = 1;
14+
for (let i = 1; i <= k; ++i) {
15+
let sum = 0;
16+
// 优化:枚举的起点和终点需要给前后的子串预留出足够的长度
17+
for (let j = i * l; j + (k - i) * l <= n; j++) {
18+
if (canPartition(s, j - l)) sum = (sum + f[i - 1][j - l]) % MOD; // j'=j-l 双指针
19+
if (canPartition(s, j)) f[i][j] = sum;
20+
}
21+
}
22+
return f[k][n];
23+
}
24+
25+
function isPrime(c: string) {
26+
return c == "2" || c == "3" || c == "5" || c == "7";
27+
}
28+
29+
// 判断是否可以在 j-1 和 j 之间分割(开头和末尾也算)
30+
function canPartition(s: string, j: number) {
31+
return j == 0 || j == s.length || (!isPrime(s[j - 1]) && isPrime(s[j]));
32+
}
33+
export default beautifulPartitions;

0 commit comments

Comments
 (0)