题目链接:https://leetcode.cn/problems/palindrome-partitioning/
方法一 回溯+ 判断回文串函数
1 方法思想
2 代码实现
class Solution {
List<List<String>> result = new ArrayList<>();
LinkedList<String> subString = new LinkedList<>();
public List<List<String>> partition(String s) {
backTraking(s, 0);
return result;
}
public void backTraking(String s, int start) {
if (start >= s.length()){
result.add(new ArrayList<>(subString));
return;
}
for (int i = start; i < s.length(); i++) {
if (isPalindrome(s, start, i)){
subString.add(s.substring(start, i + 1));
backTraking(s, i + 1);
subString.removeLast();
}
}
}
public boolean isPalindrome(String str, int start, int end) {
while (start < end) {
if (str.charAt(start++) != str.charAt(end--)) {
return false;
}
}
return true;
}
}
3 复杂度分析
时间复杂度:
空间复杂度:
4 涉及到知识点
5 总结
方法二 回溯+回文串预判断数组
1 方法思想
2 代码实现
public class Solution {
List<List<String>> result = new ArrayList<>();
LinkedList<String> subString = new LinkedList<>();
public List<List<String>> partition(String s) {
int len = s.length();
boolean[][] isPalindrome = new boolean[len][len];
for (int i = 0; i < len; i++) {
for (int j = 0; j <= i; j++) {
if (s.charAt(i) == s.charAt(j) && (i - j <= 2 || isPalindrome[j + 1][i - 1])) {
isPalindrome[j][i] = true;
}
}
}
backTraking(s, 0, isPalindrome);
return result;
}
public void backTraking(String s, int start, boolean[][] isPalindrome) {
if (start == s.length()) {
result.add(new ArrayList<>(subString));
return;
}
for (int i = start; i < s.length(); i++) {
if (isPalindrome[start][i]) {
subString.add(s.substring(start, i + 1));
backTraking(s, i + 1, isPalindrome);
subString.removeLast();
}
}
}
}
3 复杂度分析
时间复杂度:
空间复杂度: