-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindrome_partition_2.cpp
More file actions
40 lines (37 loc) · 918 Bytes
/
Palindrome_partition_2.cpp
File metadata and controls
40 lines (37 loc) · 918 Bytes
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
33
34
35
36
37
38
39
int minCut(string s) {
int n = s.size();
int *cost = new int[n+1];
for(int i=0; i<=n; i++) {
cost[i]=n-i-1;
}
int **p = new int*[n];
for(int i=0; i<n; i++) {
p[i] = new int[n];
}
for(int i=0; i<s.size(); i++) {
for(int j=0; j<s.size(); j++) {
p[i][j] = INT_MAX;
}
}
for(int i=0; i<s.size(); i++) {
p[i][i]=1;
}
for(int i=0; i+1<s.size(); i++) {
if(s[i]==s[i+1]) p[i][i+1]=1;
}
for(int len=3; len<=s.size(); len++) {
for(int i=0, j=i+len-1; j<s.size(); i++, j++) {
if(p[i+1][j-1]!=INT_MAX && s[i]==s[j]) {
p[i][j]=1;
}
}
}
for(int i=s.size()-1; i>=0; i--) {
for(int j=i; j<s.size(); j++) {
if(p[i][j]==1) {
cost[i] = min(cost[i], 1+cost[j+1]);
}
}
}
return cost[0];
}