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"] ]这种要返回所有结果的题目看起来是要用递归的,DFS暴力搜索就好了。
public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<List<String>>();
if(s == null || s.length() == 0)
return res;
dfs(s, 0, new ArrayList<String>(), res);
return res;
}
public void dfs(String s, int start, List<String> strs, List<List<String>> res){
if(start >= s.length()){
res.add(new ArrayList<String>(strs));
return;
}
for(int i = start; i < s.length(); i++){
if(isPalindrome(s, start, i)){
strs.add(s.substring(start, i + 1));
dfs(s, i + 1, strs, res);
strs.remove(strs.size() - 1);
}
}
}
public boolean isPalindrome(String s, int start, int end){
int i = start, j = end;
while(i < j){
if(s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
}