forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
palindrome-partitioning-iii.cpp
32 lines (31 loc) · 1.23 KB
/
palindrome-partitioning-iii.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
// Time: O(k * n^2)
// Space: O(n^2)
class Solution {
public:
int palindromePartition(string s, int k) {
// dp1[i][j]: minimum number of changes to make s[i, j] palindrome
vector<vector<int>> dp1(s.length(), vector<int>(s.length()));
for (int l = 1; l <= s.length(); ++l) {
for (int i = 0; i + l <= s.length(); ++i) {
int j = i + l - 1;
if (i == j - 1) {
dp1[i][j] = s[i] == s[j] ? 0 : 1;
} else if (i != j) {
dp1[i][j] = s[i] == s[j] ? dp1[i + 1][j - 1] : dp1[i + 1][j - 1] + 1;
}
}
}
// dp2[d][i]: minimum number of changes to divide s[0, i] into d palindromes
vector<vector<int>> dp2(2, vector<int>(s.length(), numeric_limits<int>::max()));
dp2[1] = dp1[0];
for (int d = 2; d <= k; ++d) {
dp2[d % 2] = vector<int>(s.length(), numeric_limits<int>::max());
for (int i = d - 1; i < s.length(); ++i) {
for (int j = d - 2; j < i; ++j) {
dp2[d % 2][i] = min(dp2[d % 2][i], dp2[(d - 1) % 2][j] + dp1[j + 1][i]);
}
}
}
return dp2[k % 2][s.length() - 1];
}
};