Original title Address
Dynamic programming questions.
The most intuitive idea is to use cut[i][j] to denote substring s[i. J] for the minimum number of divisions, there are the following rules:
1. If S[i. J] is a palindrome string, then cut[i][j]=0
2. If S[i. J] is not a palindrome string, then the enumeration points, the original string is cut into two substrings, solve the sub-problem. Recursive formula: Cut[i][j] = Min{cut[i][k] + cut[k+1][j] + 1},i <= K < J
The time complexity of doing this is O (n^3), which can be introduced with additional auxiliary conditions to optimize the recursive array dimensionality reduction.
The improvement is this:
Cut[i] denotes substring s[i. N-1] The minimum number of splits, there are the following rules:
1. If S[i. N-1] is a palindrome string, then cut[i] = 0
2. If S[i. N-1] is not a palindrome string, the enumeration of the split point, the original string into two substrings, the left of the string must be a palindrome string . Recursive formula: Cut[i] = min{cut[k] + 1},i < K < J and S[i][k-1] are palindrome strings
Time complexity reduced to O (n^2)
The above is not considered to determine the calculation of palindrome string, in fact, this part contains a large number of repeated calculations, so it is necessary to record whether it is a palindrome string, and later to judge the time to check the table directly.
The palindrome string can also be solved by moving. Make Palinp[i][j] represent s[i. J] is a palindrome, then palinp[i][j] = s[i] = = S[j] && (j-i > 2 | | palinp[i+1][j-1]), this part of the time complexity is O (n^2)
Code:
1 intMincut (strings) {2 if(S.empty ())3 return 0;4 5 intLen =s.length ();6 BOOL**PALINP =New BOOL*[Len];7 int*cut =New int[Len];8 9 for(inti =0; i < Len; i++)TenPalinp[i] =New BOOL[Len]; One A for(intL =1; L <= Len; l++) { - for(inti =0; i + L <= len; i++) { -Palinp[i][i + L-1] = (S[i] = = S[i + L-1]) && (l <=2|| Palinp[i +1][i + L-2]); the } - } - - for(inti = len-1; I >=0; i--) { + if(Palinp[i][len-1]) -Cut[i] =0; + Else { ACut[i] = len-i-1; at for(intj = i +1; J < Len; J + +) { - if(Palinp[i][j-1]) -Cut[i] = min (Cut[i],1+cut[j]); - } - } - } in - returncut[0]; to}
leetcode#132 palindrome Partitioning II