-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
partition-string-into-minimum-beautiful-substrings.cpp
62 lines (57 loc) · 1.66 KB
/
partition-string-into-minimum-beautiful-substrings.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Time: O(n^2)
// Space: O(n)
// dp
class Solution {
public:
int minimumBeautifulSubstrings(string s) {
static const int INF = numeric_limits<int>::max();
int max_pow_5 = 1;
while (max_pow_5 * 5 <= (1 << size(s)) - 1) {
max_pow_5 *= 5;
}
vector<int> dp(size(s) + 1, INF);
dp[0] = 0;
for (int i = 0; i < size(s); ++i) {
if (s[i] == '0') {
continue;
}
int curr = 0;
for (int j = i; j < size(s); ++j) {
curr = curr * 2 + (s[j] - '0') ;
if (max_pow_5 % curr == 0) {
if (dp[(i - 1) + 1] != INF) {
dp[j + 1] = min(dp[j + 1], dp[(i - 1) + 1] + 1);
}
}
}
}
return dp.back() != INF ? dp.back() : -1;
}
};
// Time: O(n^2)
// Space: O(n)
// dp
class Solution2 {
public:
int minimumBeautifulSubstrings(string s) {
static const int INF = numeric_limits<int>::max();
int max_pow_5 = 1;
while (max_pow_5 * 5 <= (1 << size(s)) - 1) {
max_pow_5 *= 5;
}
vector<int> dp(size(s) + 1, INF);
dp[0] = 0;
for (int i = 0; i < size(s); ++i) {
int curr = 0;
for (int j = i; j >= 0; --j) {
curr += (s[j] - '0') << (i - j);
if (s[j] == '1' && max_pow_5 % curr == 0) {
if (dp[(j - 1) + 1] != INF) {
dp[i + 1] = min(dp[i + 1], dp[(j - 1) + 1] + 1);
}
}
}
}
return dp.back() != INF ? dp.back() : -1;
}
};