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 =
Return
"aab"
,Return
[ ["aa","b"], ["a","a","b"] ][Analysis]
Backpacking: if the last part of string S(j, end)is a palindrome, then all combinations of the result of S(0,j) needs to add S(j, end).
[Solution]
class Solution {
public:
bool isPalindrome(string s) {
if (s.empty()) return true;
int i = 0;
int j = s.size()-1;
while (i<j) {
if(s[i++]!=s[j--]) return false;
}
return true;
}
vector<vector<string>> partition(string s) {
vector<vector<string>> ret;
if (s.empty()) return ret;
if (s.size()==1) {
ret.push_back(vector<string> (1,s));
return ret;
}
for( int i=s.size()-1; i>=0; i--) {
string second= s.substr(i);
string first = s.substr(0, i);
if (isPalindrome(second)) {
vector<vector<string>> ret1 = partition(first);
if (ret1.empty()) {
ret.push_back(vector<string>(1, second));
}
else {
for(auto& v: ret1) {
v.push_back(second);
}
}
ret.insert(ret.end(), ret1.begin(), ret1.end());
}
}
return ret;
}
};
No comments:
Post a Comment