description:
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Have you met this question in a real interview? Yes
Example
Given s = “aab”, return:
[
[“aa”,”b”],
[“a”,”a”,”b”]
]
解题思路:因为题目中是要求求出所有的元素的,而且这些元素之间是没有顺序关系的,因此使用DFS。
将题目分为3个步骤
(1)将字符串分割;
(2)判读是否为回文;
(3)返回需要的结果。
注意:代码中的start是表示外层进入循环,用来区分递归的内部进入循环!!!
public class Solution {
/**
* @param s: A string
* @return: A list of lists of string
*/
public List<List<String>> partition(String s) {
// write your code here
List<List<String>> result = new ArrayList<>();
List<String> list = new ArrayList<>();
if (s == null || s.length() == 0) {
return result;
}
util(s, 0, result, list);
return result;
}
private void util(String s,
int start,
List<List<String>> result,
List<String> list) {
if (start == s.length()) {
result.add(new ArrayList<String>(list));
return;
}
for (int i = start; i < s.length(); i++) {
String str = s.substring(start, i + 1);
if (isPartition(str)) {
list.add(str);
util(s, i + 1, result, list);
list.remove(list.size() - 1);
}
}
}
private boolean isPartition(String s) {
if (s.length() == 1) {
return true;
}
for (int i = 0, j = s.length() - 1; i <= j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}