给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
示例 1:
输入:s = “aab”
输出:[[“a”,“a”,“b”],[“aa”,“b”]]
示例 2:
输入:s = “a”
输出:[[“a”]]
提示:
1 <= s.length <= 16
s 仅由小写英文字母组成
思路: dfs + 记忆化搜索
- dfs 递归当前 start 下标开始的字串能如何划分,枚举其右边界
- 如果当前字串是回文串,则将当前字串加入当前dfs路径,dfs 继续递归剩余的字串
- 当前路径递归完,遍历下个边界时,需要回溯,删除路径列表中之前的字串
- 如果递归到 start==n,即已经划分完所有的字串,则将当前路径加入结果集
- 判断回文串,可以通过记忆化搜索,f[i][j] 用于记录当前状态是否判断过
- 其中 1 代表是回文串,0 代表不是,-1 代表还没有搜索过
class Solution {
public:
vector<vector<string>> res;
int f[20][20];
vector<vector<string>> partition(string s) {
vector<string> ans;
memset(f, -1, sizeof f);
dfs(s, 0, ans);
return res;
}
void dfs(string &s, int idx, vector<string> &ans){
if(idx >= s.size()){
res.push_back(ans);
return;
}
for(int i = idx; i <= s.size() - 1; i++){
string curStr = s.substr(idx, i - idx + 1);
if(is_fn(s, idx, i)){
ans.push_back(curStr);
dfs(s, i + 1, ans);
ans.pop_back();
}
}
}
int is_fn(string &s, int l, int r){
if(r - l <= 1) return f[l][r] = (s[l] == s[r]);
if(f[l][r] >= 0) return f[l][r];
return f[l][r] = (s[l] == s[r] && is_fn(s, l+1, r-1));
}
};