File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed
number-of-beautiful-partitions Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -45,6 +45,8 @@ Step 2. Add the dependency
45
45
46
46
<summary >展开查看</summary >
47
47
48
+ https://leetcode.cn/problems/number-of-beautiful-partitions
49
+
48
50
https://leetcode.cn/problems/minimum-fuel-cost-to-report-to-the-capital
49
51
50
52
https://leetcode.cn/problems/closest-nodes-queries-in-a-binary-search-tree
Original file line number Diff line number Diff line change
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 ;
You can’t perform that action at this time.
0 commit comments