难度中等592
给你一个字符串 s
,请你将 s
分割成一些子串,使每个子串都是 回文串 。返回 s
所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
示例 1:
输入:s = "aab" 输出:[["a","a","b"],["aa","b"]]
示例 2:
输入:s = "a" 输出:[["a"]]
class Solution {
public:
vector<vector<string>> res; //都整成全局变量,免得回溯的时候传来传去的
vector<string> tmp;
vector<vector<string>> partition(string s) {
dfs(s);
return res;
}
void dfs(string s)
{
if (s.size() == 0) //字符串已经分割完,当前路径存到结果中
{
res.push_back(tmp);
return;
}
for (int i = 1; i <= s.size(); i ++ )
{
string str = s.substr(0, i);
if (check(str))
{
tmp.push_back(str);
dfs(s.substr(i)); //去掉前i个字符,继续递归
tmp.pop_back(); //恢复现场
}
}
}
bool check(string s) //判断回文字符串模板
{
int l = 0, r = s.size() - 1;
while (l <= r)
{
if (s[l] != s[r])
return false;
l ++ , r -- ;
}
return true;
}
};