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"]
]
Solution:
Code:
<span style="font-size:14px;">class Solution {
public:
void helper(vector<vector<string> > &results, vector<string> &result, const string &s, int index, bool **dp) {
if (index == s.size()) {
results.push_back(result);
return;
}
for (int i = index; i < s.size(); ++i)
if (dp[index][i]) {
result.push_back(s.substr(index, i-index+1));
helper(results, result, s, i+1, dp);
result.pop_back();
}
}
vector<vector<string>> partition(string s) {
const int length = s.size();
bool **dp = new bool *[length];
for (int i = 0; i < length; ++i) {
dp[i] = new bool[length];
memset(dp[i], false, sizeof(bool)*length);
dp[i][i] = true;
}
for (int i = 1; i < length; ++i)
for (int j = 0; j < i; ++j)
if (s[i] == s[j] && (i-j < 3 || dp[j+1][i-1]))
dp[j][i] = true;
vector<vector<string> > results;
vector<string> result;
helper(results, result, s, 0, dp);
return results;
}
};</span>