Palindrome Partitioning II
https://leetcode.com/problems/palindrome-partitioning-ii/description/
Thoughts
Code
/*
* @lc app=leetcode id=132 lang=cpp
*
* [132] Palindrome Partitioning II
*/
class Solution {
public:
vector<vector<bool>> isPalindrome(string s) {
const int N = s.size();
vector<vector<bool>> dp(N, vector<bool>(N));
for (int i = 0; i < N; ++i) dp[i][i] = true;
for (int i = N; i >= 0; --i) {
for (int j = i + 1; j < N; ++j) {
if (s[i] == s[j] && (j == i + 1 || dp[i + 1][j - 1])) dp[i][j] = true;
}
}
return dp;
}
int minCut(string s) {
const int N = s.size();
const auto &palind = isPalindrome(s);
vector<int> dp(N);
for (int j = 1; j < N; ++j) {
if (palind[0][j]) {
dp[j] = 0;
continue;
}
dp[j] = dp[j - 1] + 1;
for (int i = 0; i < j; ++i) {
if (palind[i][j]) dp[j] = min(dp[j], dp[i - 1] + 1);
}
}
return dp[N - 1];
}
};
Analysis
Last updated