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"]
]
思路:遇见return all, generate all就是backtracking。NP问题,循环里面调用递归函数。
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> lists = new ArrayList<List<String>>();
List<String> list = new ArrayList<>();
dfs(s, 0, list, lists);
return lists;
}
private void dfs(String s, int index, List<String> list, List<List<String>> lists) {
if(index == s.length()) {
lists.add(new ArrayList<>(list));
return;
}
for(int i = index; i < s.length(); i++) {
String substr = s.substring(index, i + 1);
if(isPalindrome(substr)) {
list.add(substr);
dfs(s, i + 1, list, lists);
list.remove(list.size() - 1);
}
}
}
private boolean isPalindrome(String s) {
int i = 0; int j = s.length() - 1;
while(i <= j) {
if(s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}