直接使用DFS硬怼
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab"
,
Return
[ ["aa","b"], ["a","a","b"] ]
java
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
if (s == null || s.length() == 0) {
return result;
}
dfs(s, 0, new ArrayList<String>(), result);
return result;
}
private void dfs(String s, int start, List<String> path, List<List<String>> result) {
if (start == s.length()) {
result.add(new ArrayList<String>(path));
return;
}
for (int i = start; i < s.length(); i++) {
String str = s.substring(start, i + 1);
if (!isPal(str)) {
continue;
} else {
path.add(str);
dfs(s, i + 1, path, result);
path.remove(path.size() - 1);
}
}
}
private boolean isPal(String s) {
if (s.length() == 1) {
return true;
}
int left = 0;
int right = s.length() - 1;
while (left <= right) {
if (s.charAt(left++) != s.charAt(right--)) {
return false;
}
}
return true;
}
}