题目描述
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"] ]
解题思路:
- dp数组记录任意子串是否是回文
- dfs搜索
import java.util.*;
public class Solution {
int[][] dp;
String str;
ArrayList<ArrayList<String>> reverse = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
public ArrayList<ArrayList<String>> partition(String s) {
int len = s.length();
dp = new int[len][len];
str = s;
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
if (isPalindrome(s.substring(i, j + 1))) {
dp[i][j] = 1;
}
}
}
dfs(len - 1, "");
for (int i = reverse.size() - 1; i >= 0; i--) {
res.add(reverse.get(i));
}
return res;
}
public void dfs(int length, String pre) {
if (length == -1) {
String[] ps = pre.split(":");
ArrayList<String> t = new ArrayList<String>();
for (int i = 0; i < ps.length; i++) {
t.add(ps[i]);
}
reverse.add(t);
return;
}
for (int i = 0; i <= length; i++) {
if (dp[i][length] == 1) {
String pnext = pre.equals("")? str.substring(i, length + 1) : str.substring(i, length + 1) + ":" + pre;
dfs(i-1, pnext);
}
}
}
public boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i ++;
j --;
}
return true;
}
}