-
Notifications
You must be signed in to change notification settings - Fork 9
/
Palindrome_Partn.cpp
76 lines (68 loc) · 1.35 KB
/
Palindrome_Partn.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
67
68
69
70
71
72
73
74
75
76
#include <bits/stdc++.h>
using namespace std;
int static t[1001][1001];
/* Palindrome Partitioning
I/O:
GEKES -> G|EKE|S (minimum 2 partition and each partiotion is palindrome)
O/P:
2
**/
bool isPalindrome(string s, int i, int j)
{
if (i >= j)
return true;
while (i < j)
{
if (s[i] == s[j])
{
i++;
j--;
}
else
{
return false;
}
}
return true;
}
int solve(string s, int i, int j)
{
if (t[i][j] != -1)
return t[i][j];
if (i >= j)
return 0;
if (isPalindrome(s, i, j))
return 0;
int m = INT_MAX;
for (int k = i; k < j; k++)
{
// for further optimisation check whether "sub-functions" are already called or not.
int l, r;
if (t[i][k] != -1)
l = t[i][k];
else
{
l = solve(s, i, k);
t[i][k] = l;
}
if (t[k + 1][j] != -1)
r = t[k + 1][j];
else
{
r = solve(s, k + 1, j);
t[k + 1][j] = r;
}
// int temp = solve(s, i, k) + solve(s, k + 1, j) + 1;
int temp = l + r + 1;
m = min(temp, m);
}
return t[i][j] = m;
}
int main()
{
memset(t, -1, sizeof(t));
string s;
cin >> s;
cout << solve(s, 0, s.length() - 1);
return 0;
}