131. 分割回文串
题目描述
思路分析
区间dp预处理f+暴搜
f
[
i
]
[
j
]
:
[
i
,
j
]
f[i][j]:[i,j]
f[i][j]:[i,j]是否是回文串
代码实现
class Solution {
public:
vector<vector<bool>> f;
vector<vector<string>> ans;
vector<string> path;
vector<vector<string>> partition(string s) {
int n=s.size();
f=vector<vector<bool>>(n,vector<bool>(n));
for(int i=0;i<n;i++) f[i][i]=true;
for(int len=2;len<=n;len++){
for(int l=0;l+len-1<n;l++){
int r=l+len-1;
if(s[l]==s[r]&&(l+1==r||f[l+1][r-1])) f[l][r]=true;
}
}
dfs(s,0);
return ans;
}
void dfs(string &s,int u){
if(u==s.size()){
ans.push_back(path);
return;
}
for(int i=u;i<s.size();i++){
if(f[u][i]){
path.push_back(s.substr(u,i-u+1));
dfs(s,i+1);
path.pop_back();
}
}
}
};