题目:Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = “aab”, Return
[
[“aa”,”b”],
[“a”,”a”,”b”]
]
代码如下:
// 动态规划,时间复杂度 O(n^2),空间复杂度 O(n^2)
// 不仅判断 s 的各个子字符串s[i, j] 是否为回文
// 同时还给出 s 的所有回文字段
class Solution {
public:
vector<vector<string>> partition(string s) {
const int n = s.size();
bool table[n][n] = { true }; // s[i, j] 是否为回文
// sub_palins[i] 表示子字符串 s[i, n) 中的一段段回文
vector<vector<string>> sub_palins[n];
for (int i = n - 1; i >= 0; --i)
for (int j = i; j <= n - 1; ++j) {
int l = j - i + 1;
if (l == 1) table[i][j] = true;
else if (l == 2) table[i][j] = s[i] == s[j];
else table[i][j] = table[i + 1][j - 1] && (s[i] == s[j]);
if (table[i][j]) {
const string palindrome = s.substr(i, j - i + 1);
if (j == n - 1) sub_plains[i].push_back(vector<string>{palindrome});
else {
for (auto v : sub_palins[j + 1]) {
v.insert(v.begin(), palindrome);
sub_palins[i].push_back(v);
}
}
}
}
return sub_palins[0];
}
};