-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromicPartioningLecture53.cpp
More file actions
77 lines (75 loc) · 1.61 KB
/
Copy pathPalindromicPartioningLecture53.cpp
File metadata and controls
77 lines (75 loc) · 1.61 KB
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
#include <vector>
#include <iostream>
#include <algorithm>
#include <climits>
using namespace std;
//https://bit.ly/3jNRzqX
bool isPalindrome(int i,int j,string &s)
{
while(i < j)
{
if(s[i] != s[j]) return false;
i++;j--;
}
return true;
}
int solve1(int i,int n,string &str)
{
if(i == n) return 0;
int minCost = INT_MAX;
// i...j
for(int j = i;j < n;j++)
{
if(isPalindrome(i, j, str))
{
int cost = 1 + solve1(j + 1,n,str);
minCost = min(minCost,cost);
}
}
return minCost;
}
int solve2(int i,int n,string &str,vector<int> &dp)
{
if(i == n) return 0;
int minCost = INT_MAX;
if(dp[i] != -1) return dp[i];
// i...j
for(int j = i;j < n;j++)
{
if(isPalindrome(i, j, str))
{
int cost = 1 + solve2(j + 1,n,str,dp);
minCost = min(minCost,cost);
}
}
return dp[i] = minCost;
}
int solve3(string &str)
{
int n = str.size();
vector<int> dp(n+1,-1);
dp[n] = 0;
for(int i = n-1;i >= 0;i--)
{
int minCost = INT_MAX;
for(int j = i;j < n;j++)
{
if(isPalindrome(i, j, str))
{
int cost = 1 + solve2(j + 1,n,str,dp);
minCost = min(minCost,cost);
}
}
dp[i] = minCost;
}
return dp[0]- 1;
}
int palindromePartitioning(string str)
{
int n = str.size();
// vector<int> dp(n+1,-1);
// return solve1(0,n,str,dp) - 1;
// does a partition at the end so we have to
// subtract 1 from the answer
return solve3(str);
}