39. Palindrome Partitioning II
Input: s = "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.Input: s = "a"
Output: 0Input: s = "ab"
Output: 1Solution:
Solution:
Last updated
Input: s = "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.Input: s = "a"
Output: 0Input: s = "ab"
Output: 1Last updated
class Solution
{
public:
int minCut(string s)
{
int n = s.length();
vector<vector<bool>> palen(n, vector<bool>(n, false));
vector<int> dp(n + 1);
for (int i = 0; i <= n; i++)
{
dp[i] = i - 1;
}
for (int i = 0; i < n; i++)
{
for (int j = i; j >= 0; j--)
{
if (i - j == 0)
{
palen[i][j] = true;
dp[i + 1] = min(dp[i] + 1, dp[i + 1]);
}
if (i - j == 1)
{
if (s[i] == s[j])
{
palen[j][i] = true;
dp[i + 1] = min(dp[j] + 1, dp[i + 1]);
}
}
if (i - j > 1)
{
if (s[i] == s[j] && palen[j + 1][i - 1])
{
palen[j][i] = true;
dp[i + 1] = min(dp[i + 1], dp[j] + 1);
}
}
}
}
return dp[n];
}
};