题意:找到字符串中所有的回文。
思路:DFS,暴力搜索。
class Solution {
public:
vector<vector<string>> re;
vector<vector<string>> partition(string s) {
vector<string> ss;
dfs(ss, s);
return re;
}
bool isP(string s) {
for(int i = 0; i < s.length() / 2; ++ i) {
if(s[i] != s[s.length() - i - 1]) return false;
}
return true;
}
void dfs(vector<string> rre, string s) {// cout << s << endl;
if(s.length() == 0) {
re.push_back(rre);
return;
}
string s1;
for(int i = 0; i < s.length(); ++ i) {
s1 = s.substr(0, i + 1); //cout << i << endl;
//cout << s.substr(i + 1, s.length() - i - 1) << endl;
if(isP(s1)) {
vector<string> temp = rre;
temp.push_back(s1); //for(int j = 0; j < rre.size(); j ++) cout << rre[j] << endl; cout << endl;
dfs(temp, s.substr(i + 1, s.length() - i - 1));
}
}
return;
}
};
此题还有DP的方法,值的思考。
本文介绍了一种使用深度优先搜索(DFS)的方法来找出字符串中的所有回文子串,并提供了一个C++实现的例子。同时提到了该问题还可以通过动态规划(DP)的方法进行求解。
210

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



