Problem:
Given A string s, partition s such that every substring of the partition are a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab" ,
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.
Hide TagsDynamic ProgrammingTest instructions: To divide a string into the minimum number of substrings that each substring is a literal string
Thinking:
(1) Optimal solution, DP problem
(2)Defining Functions
D[i,n] = minimum cut number between interval [I,n], n is string length
a b A b b b a b b a B a
i n
What if we now seek the optimal solution between [i,n]? How much should it be? Simply take a look at at least one of the following solutions
a b A b b b a b b a B a
IJ j+1N
at this time d[i,n] = min (D[i, J] + D[j+1,n]) i<=j <n. This is a two-dimensional function that is cumbersome to maintain when actually writing code. So we're going to convert to one-dimensional DP. If every time, from I to the right scan, each found a palindrome even if a DP, you can convert to
D[i] = The minimum cut number between the interval [i,n] and N is the string length, then the
D[i] = min (1+d[j+1]) i<=j <n
after having a transfer function, a problem arises, that is, how to tell if [I,j] is a palindrome? Each time from I to J compare again? Too wasteful, this is also a DP problem.
Defining Functions
P[i][j] = True if [I,j] is a palindrome
so
P[i][j] = ((str[i] = = Str[j]) && (p[i+1][j-1]));
Code
Class Solution{public:int Mincut (string s) { int len = S.size (); int* dp = new int[len+1];for (int i=len; i>=0; i--) d P[i] = len-i;bool** matrix = new Bool*[len];for (int i=0; i<len; i++) {Matrix[i] = new Bool[len];memset (Matrix[i], False, sizeof (BOOL) *len);} for (int i=len-1, i>=0; i--) for (int j=i; j<len; J + +) {if (s[i] = = S[j] && (j-i<2 | | matrix[i+1][j-1])) {Matri X[I][J] = true;dp[i] = min (dp[i], dp[j+1]+1);}} return dp[0]-1;} ;
Leetcode | | 132, Palindrome partitioning II