Description:
Given a string s, partition s such that every substring of the partition is 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.
分析:求字符串的最小切,简单来看 对每一个新字符,往前找到它组成的所有回文,保留最小值,遍历整个字符串,即可以得到最小切得结果。
这里往前找,会将字符串分成两部分,带当前字符的回文部分,和前面的字符串部分。这样就会带来大量的重复子问题,当然考虑是动态规划来做。
动态规划的递归式是: F(x) = min{F(j)+1} for all j,s.t string [j+1,x] is a palindrome.
这里还有一个技巧需要注意,因为此时我们就需要判断一个字符串是否是回文串,判断方法也应该用动态规划来做,否则会超时。 判断回文的动归
比较简单,递归式是 B[i][j] = (s[i]==s[j]) && B[i+1][j-1]
然后是代码:
1 class Solution {
2 public:
3 int minCut(string s) {
4 //初步感觉是动态规划来做,每次多进来一个字符,去看他跟之前元素的最长匹配串,并
5 //和他单独割开比较,取最小值,记录下来。
6 if(s.size()<2) return 0;
7 int sz = s.size();
8 int *record = new int[s.size()];
9 vector<vector<bool> > palinrec(sz,vector<bool>(sz,false));
10
11 memset(record,0,sizeof(record));
12
13 for(int i=1;i<s.size();i++)
14 {
15 int index;
16 for(int j=i;j>=0;--j)
17 {
18 if(tellpalin(s,j,i,palinrec))
19 {
20 index = j;
21 if(index==i)
22 {
23 record[i] = record[i-1]+1;
24 }
25 else if(index>0)
26 {
27 record[i] = min(record[index - 1] + 1, record[i]);
28 }
29 else{
30 record[i]=0;
31 }
32 }
33 }
34 }
35 return record[s.size()-1];
36
37 }
38 bool tellpalin(string &s, int left,int right,vector<vector<bool> >&palinrec)
39 {
40 bool flag = true;
41 if(s[left]!=s[right])
42 {
43 palinrec[left][right]=0;
44 return false;
45 }
46 if( (left+1) < (right-1))
47 {
48 flag = palinrec[left+1][right-1];
49 }
50 palinrec[left][right] = flag;
51 return flag;
52 }
53
54 };
来源:https://www.cnblogs.com/soyscut/p/3863714.html