link
https://leetcode-cn.com/problems/palindrome-partitioning-ii/
time consuming
Problem solving: 32 min
Problem solving: 25 min
Title
Give you a string s, please split s into some substrings so that each substring is a palindrome.
Returns the minimum number of splits that meet the requirements.
Ideas
dp[i] represents the minimum number of divisions of the string of s[0:i].
dp [i] = {0 (s [0: i] is a palindrome) min j = 0 i − 1 (dp [j] + 1) when s [j + 1: i] is a palindrome Next (s [0: i] is not a palindrome string) dp[i] = \begin{cases} 0 \ \ \ \ \ \ \ \ \ \ (s[0:i] is a palindrome string) \\ \min_ {j=0}^{i-1}(dp[j]+1) When s[j+1:i] is a palindrome \ \ (s[0:i] is not a palindrome) \ end{cases} dp[i]={ 0 (s[0:I ] a return text string )minj=0i−1(dp[j]+1 ) in s ( j+1:I ] a return text string is case conditions under ( S [ 0 :I ] is not a return to the text string )
Judge the palindrome string, is_palindrome[i][j] indicates whether s[i:j] is a palindrome string.
i s _ p a l i n d r o m e [ i ] [ j ] = { t r u e , i ≥ j i s _ p a l i n d r o m e [ i + 1 ] [ j − 1 ] ∧ s [ i ] = = s [ j ] , o t h e r w i s e is\_palindrome[i][j] = \begin{cases} true, i \geq j \\ is\_palindrome[i+1][j-1] \wedge s[i] == s[j], otherwise \end{cases} is_palindrome[i][j]={ true,i≥jis_palindrome[i+1][j−1]∧s[i]==s[j],otherwise
Time complexity: O (n 2) O(n^2)O ( n2)
AC code
class Solution {
public:
int minCut(string s) {
int n = s.size();
vector<vector<bool>> is_palindrome(n, vector<bool>(n, true));
for(int i = n-1; i >= 0; --i) {
for(int j = i+1; j < n; ++j) {
is_palindrome[i][j] = (is_palindrome[i+1][j-1] && s[i] == s[j]);
}
}
vector<int> dp(n, n-1);
dp[0] = 0;
for(int i = 1; i < n; ++i) {
if(is_palindrome[0][i]) {
dp[i] = 0;
}
else {
for(int j = 0; j < i; ++j) {
if(is_palindrome[j+1][i]) {
dp[i] = min(dp[i], dp[j]+1);
}
}
}
}
return dp[n-1];
}
};