题目:牛客网
搜索问题主要使用回溯法。
回溯法思考的步骤:
1、画递归树;
2、根据自己画的递归树编码。
import java.util.ArrayList;
public class Main {
public static boolean isPalindrome(String s) {
if (null == s || s.length() == 0)
return false;
int length = s.length();
int middle = length / 2;
for (int i = 0; i < middle;i++) {
if (s.charAt(i) != s.charAt(length - 1 - i)) {
return false;
}
}
return true;
}
public static ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> res = new ArrayList<>();
ArrayList<String> list = new ArrayList<>();
partitionHepler(res, list, s);
return res;
}
public static void partitionHepler(ArrayList<ArrayList<String>> res, ArrayList<String> list, String s) {
//当字符串为空或长度为0时,add list
if (null == s || s.length() == 0) {
res.add(new ArrayList<>(list));
return;
}
int len = s.length();
for (int i = 1; i <= len; i++) {
String subStr = s.substring(0, i);
if (isPalindrome(subStr)) {
list.add(subStr);
partitionHepler(res, list, s.substring(i, len));
list.remove(list.size() - 1);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(partition("aab"));
}
}