/*采用深度搜索算法。
写法一。*/
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string> > res;
if(s.empty()) return res;
vector<string> path;
partition(s, res, path, -1, 0);
return res;
}
void partition(const string &s, vector<vector<string> > &res, vector<string> &path, int pre, int cur){
if(cur == s.size()-1){
if(is_palindrome(s, pre+1, cur)){
path.push_back(s.substr(pre+1, cur-pre));
res.push_back(path);
path.pop_back();
}
return;
}
else{
if(is_palindrome(s, pre+1, cur)){
path.push_back(s.substr(pre+1, cur-pre));
partition(s, res, path, cur, cur+1);
path.pop_back();
}
partition(s, res, path, pre, cur+1);
}
}
bool is_palindrome(const string &s, int left, int right){
if(left >= right) return true;
while(left < right){
if(s[left] != s[right]) return false;
++left;
--right;
}
return true;
}
};
/*写法二。*/
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string> > res;
if(s.empty()) return res;
vector<string> path;
partition(s, res, path, 0);
return res;
}
void partition(const string &s, vector<vector<string> > &res, vector<string> &path, int cur){
if(cur == s.size()){
res.push_back(path);
return;
}
else{
for(int i = cur; i < s.size(); ++i){
if(is_palindrome(s, cur, i)){
path.push_back(s.substr(cur, i-cur+1));
partition(s, res, path, i+1);
path.pop_back();
}
}
}
}
bool is_palindrome(const string &s, int left, int right){
if(left >= right) return true;
while(left < right){
if(s[left] != s[right]) return false;
++left;
--right;
}
return true;
}
};
LeetCode之Palindrome Partitioning
最新推荐文章于 2019-07-19 22:24:44 发布