題目
給定一個字符串s,將s分割成一些子串,使每個子串都是回文串。
返回s所有可能的回文串分割方案颂郎。
樣例
給出 s = "aab",返回
[
["aa", "b"],
["a", "a", "b"]
]
分析
這是一道很綜合的題目容为,結(jié)合了動態(tài)規(guī)劃乓序,深度搜索和回溯法。
首先為了分割出回文串坎背,我們首先要寫出判斷回文串的方法替劈,這里使用動態(tài)規(guī)劃來判斷回文串,而且可以存儲子串的回文串的情況得滤。
isPalindrome[i][j]:表示i到j(luò)的子串是否是回文串陨献。
狀態(tài)轉(zhuǎn)移方程:
isPalindrome[i][j] = isPalindrome[i+1][j-1] && s.charAt(i) == s.charAt(j)
自然如果一個串是回文串,那么首尾必須要相等懂更,并且中間也是子串眨业。
初始化急膀,顯然當i==j的時候都是回文串
當串只有兩個字符且相等的時候也是回文串。
知道如何判斷子串是否是回文串就好辦了龄捡,然后只要模式化的深度搜索回溯即可
代碼
public class Solution {
/**
* @param s: A string
* @return: A list of lists of string
*/
List<List<String>> results;
boolean[][] isPalindrome;
/**
* @param s: A string
* @return: A list of lists of string
*/
public List<List<String>> partition(String s) {
results = new ArrayList<>();
if (s == null || s.length() == 0) {
return results;
}
getIsPalindrome(s);
helper(s, 0, new ArrayList<Integer>());
return results;
}
private void getIsPalindrome(String s) {
int n = s.length();
isPalindrome = new boolean[n][n];
for (int i = 0; i < n; i++) {
isPalindrome[i][i] = true;
}
for (int i = 0; i < n - 1; i++) {
isPalindrome[i][i + 1] = (s.charAt(i) == s.charAt(i + 1));
}
for (int i = n - 3; i >= 0; i--) {
for (int j = i + 2; j < n; j++) {
isPalindrome[i][j] = isPalindrome[i + 1][j - 1] && s.charAt(i) == s.charAt(j);
}
}
}
private void helper(String s,
int startIndex,
List<Integer> partition) {
if (startIndex == s.length()) {
addResult(s, partition);
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (!isPalindrome[startIndex][i]) {
continue;
}
partition.add(i);
helper(s, i + 1, partition);
partition.remove(partition.size() - 1);
}
}
private void addResult(String s, List<Integer> partition) {
List<String> result = new ArrayList<>();
int startIndex = 0;
for (int i = 0; i < partition.size(); i++) {
result.add(s.substring(startIndex, partition.get(i) + 1));
startIndex = partition.get(i) + 1;
}
results.add(result);
}
}