思路:很显然的深度搜索,如果当前子串是回文串,继续从子串末尾的下一个字符开始搜索。
code:
class Solution {
public:
bool isPalindrome(string s, int n){
if(n == 1)return true;
int l = 0, r = n - 1;
while(l < r)
if(s[l++] != s[r--])
return false;
return true;
}
void dfs(int start,int n,vector<vector<string>> &ret, vector<string> &curStr, string s){
if(start == n){
ret.push_back(curStr);
return;
}
for(int i = start;i < n;i++){
string temp = s.substr(start,i-start+1);
if(isPalindrome(temp,i-start+1)){
vector<string> str(curStr);
str.push_back(temp);
dfs(i+1,n,ret,str,s);
}
}
}
vector<vector<string>> partition(string s) {
vector<vector<string>> ret;
int n = s.length();
vector<string> curStr;
dfs(0,n,ret,curStr,s);
return ret;
}
};
本文介绍了一种使用深度优先搜索算法来解决字符串分割成多个回文子串的问题的方法。通过递归地检查子串是否为回文,并将它们添加到结果集中,实现了有效的回文串分割方案。
330

被折叠的 条评论
为什么被折叠?



