class Solution {
//要返回的答案
List<List<String>> ans = new ArrayList<>();
List<String> path = new ArrayList<>();
int n ;
//g[i][j]表示s[i,j]是否是回文串
boolean[][] g;
public List<List<String>> partition(String s) {
this.n = s.length();
g = new boolean[n][n];
for(int j = 0; j < n; j++){
for(int i = 0; i <= j; i++){
//s[i,i]
if(i == j) g[i][j] = true;
//s[i]=s[j] && (s[i - 1][j - 1] == true || i + 1 = j)
else if(s.charAt(i) == s.charAt(j)){
if(i + 1 == j || g[i + 1][j - 1]) g[i][j] = true;
}
}
}
//从s串的第u个位置开始,表示s[0,u]可以分割的字符串情况
dfs(s,0);
return ans;
}
public void dfs(String s, int u){
if(u == n){
ans.add(new ArrayList<>(path));
return;
}
for(int i = u; i < n; i++){
if(!g[u][i]) continue;
path.add(s.substring(u, i + 1));
dfs(s,i + 1);
path.remove(path.size() - 1);
}
}
}
leetcode 131. 分割回文串
最新推荐文章于 2024-09-08 20:02:08 发布