[AlgoExpert] Palindrome Partitioning Min Cuts

Palindrome Partitioning Min Cuts

  • Time : O(n^2)
  • Space : O(n^2)
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
#include <vector>
using namespace std;
bool palindrome(string& s, int l, int r) {
while(l < r) {
if(s[l++] != s[r--]) return false;
}
return true;
}

int helper(string& s, vector<vector<int>>& dp, int l, int r) {
if(l >= r) return 0;
if(dp[l][r] != -1) return dp[l][r];
dp[l][r] = r - l + 1;
if(palindrome(s,l,r)) dp[l][r] = 0;
else {
for(int i = l; i < r; i++) {
if(palindrome(s, l, i)) {
dp[l][r] = min(dp[l][r], 1 + helper(s, dp, i + 1, r));
}
}
}

return dp[l][r];
}

int palindromePartitioningMinCuts(string string) {
int n = string.length();
vector<vector<int>> dp(n, vector<int>(n, -1));

return helper(string, dp, 0, n - 1);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/palindrome-partitioning-min-cuts/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.