-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathPalindrome Partitioning II.cpp
66 lines (52 loc) · 1.53 KB
/
Palindrome Partitioning II.cpp
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Solution {
public:
// function to precompute if every substring of s is a palindrome or not
vector<vector<bool>> isPalindrome(string& s){
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n, false));
for(int i=0; i<n; i++){
dp[i][i] = true;
}
for(int i=0; i<n-1; i++){
if(s[i] == s[i+1]){
dp[i][i+1] = true;
}
}
int k = 2;
while(k < n){
int i=0;
int j=k;
while(j<n){
if(s[i] == s[j] and dp[i+1][j-1]){
dp[i][j] = true;
}
i++;
j++;
}
k++;
}
return dp;
}
// function to find the minimum palindromic substrings in s
int solve(string& s, int n, int i, vector<vector<bool>>& palin, vector<int>& memo){
if(i==n){
return 0;
}
if(memo[i] != -1){
return memo[i];
}
int result = INT_MAX;
for(int j=i+1; j<=n; j++){
if(palin[i][j-1]){
result = min(result, 1+solve(s, n, j, palin, memo));
}
}
return memo[i] = result;
}
int minCut(string s) {
int n = s.size();
vector<int> memo(n, -1);
vector<vector<bool>> palin = isPalindrome(s);
return solve(s, n, 0, palin, memo)-1;
}
};