131. Palindrome Partitioning - cocoder39/coco39_LC GitHub Wiki
the helper()
takes O(n) to check if a substring is a palindrome, which can be optimized through preprocessed by dp. we can record the partition point that can produce palindrome. dp[i][j] = true iff s[i .. j] is a palindrome. Anyway, the time complexity is O(n * 2^n) for the worst case where s is "aaaaa...."
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
vector<string> cur;
helper(res, cur, s, 0);
return res;
}
private:
void helper(vector<vector<string>>& res, vector<string>& cur, string& s, int start) {
if (start == s.length()) {
res.push_back(cur);
return;
}
for (int i = start; i < s.length(); i++) {
if (isPalindrome(s, start, i)) {
string str = s.substr(start, i - start + 1);
cur.push_back(str);
helper(res, cur, s, i + 1);
cur.pop_back();
}
}
}
bool isPalindrome(string& s, int start, int end) {
while (start < end) {
if (s[start] != s[end]) {
return false;
}
start++;
end--;
}
return true;
}
};
dp records the range that is a palindrome, thus saving the O(n) palindrome check. time is O(n ^ 2 + 2 ^ n) = O(2 ^ n)
class Solution {
public:
vector<vector<string>> partition(string s) {
int len = s.length();
vector<vector<bool>> isPal(len, vector<bool>(len));
for (int i = 0; i < len; i++) {
isPal[i][i] = true;
if (i > 0 && s[i - 1] == s[i]) {
isPal[i - 1][i] = true;
}
}
for (int l = 3; l <= len; l++) {
for (int i = 0; i - 1 + l < len; i++) {
int j = i - 1 + l;
//i + 1 <= j - 1 => j - i + 1 >= 3 => l = 1, 2 are basecase
isPal[i][j] = (isPal[i + 1][j - 1] && s[i] == s[j]);
}
}
vector<vector<string>> res;
vector<string> cur;
helper(res, cur, s, 0, isPal);
return res;
}
private:
void helper(vector<vector<string>>& res, vector<string>& cur, string& s, int start, vector<vector<bool>>& isPal) {
if (start == s.length()) {
res.push_back(cur);
return;
}
for (int i = start; i < s.length(); i++) {
if (isPal[start][i]) {
cur.push_back(s.substr(start, i - start + 1));
helper(res, cur, s, i + 1, isPal);
cur.pop_back();
}
}
}
};
unlike word break, here vector cutable does not help since each position is cutable (each input has at least one solution which contains only single char)