-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day-11-palindrome-partitioning-ii.cpp
82 lines (77 loc) · 2.2 KB
/
Day-11-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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class Solution
{
public:
bool isPalindrome(string &s, int start, int end)
{
// cout<<s.substr(start, end-start+1)<<endl;
for (int i = start, j = end; i < j; i++, j--)
{
if (s[i] != s[j])
{
return false;
}
}
return true;
}
int solve(int index, string &s, vector<int> &dp)
{
// base case
if (index >= s.length())
{
return 0;
}
// dp check
if (dp[index] != -1)
return dp[index];
// redundant call check
if (isPalindrome(s, index, s.length() - 1))
return dp[index] = 1;
int ans = 1e9;
// placing the partion at various indexes
for (int i = index; i < s.length(); i++)
{
// we don't need the actual strings, so we don't make substrings --> just check
// for palindrome
int start = index, end = i;
if (isPalindrome(s, start, end))
{
ans = min(ans, 1 + solve(i + 1, s, dp));
}
}
return dp[index] = ans;
}
int minCut(string s)
{
// similar to palindrome partitioning:
int n = s.length();
// we can remove ovelapping subproblems:
// memoization:
// vector<int> dp(n, -1);
// return solve(0, s, dp) - 1;
// tabulation:
vector<int> dp(n + 1, 0);
for (int index = n - 1; index >= 0; index--)
{
// redundant call check
if (isPalindrome(s, index, s.length() - 1))
{
dp[index] = 1;
continue;
}
int ans = 1e9;
// placing the partion at various indexes
for (int i = index; i < s.length(); i++)
{
// we don't need the actual strings, so we don't make substrings --> just check
// for palindrome
int start = index, end = i;
if (isPalindrome(s, start, end))
{
ans = min(ans, 1 + dp[i + 1]);
}
}
dp[index] = ans;
}
return dp[0] - 1;
}
};