力扣链接:. - 力扣(LeetCode)
class Solution {
List<List<String>> ans = new ArrayList<>();
List<String> temp = new ArrayList<>();
String s;
public List<List<String>> partition(String s) {
this.s = s;
dfs(0);
return ans;
}
void dfs(int st) {
if(st == s.length()) {
ans.add(new ArrayList(temp));
return ;
}
//注意,substring是左闭右开,所以是i<=s.length()
for(int i=st+1;i<=s.length();i++) {
String now = s.substring(st, i);
if(check(now)) {
temp.add(now);
dfs(i);
temp.remove(temp.size()-1);
}
}
}
boolean check(String str) {
int len = str.length();
for(int i=0;i<len/2+1;i++){
if(str.charAt(i)!=str.charAt(len-i-1)){
return false;
}
}
return true;
}
}