1.题目
2. 题解
- 类似全排列问题,回溯算法解决
- startIndex为切割起点,i为切割终点
直接回溯三部曲:
- 递归函数返回值——一般是void,backTraking()
- 确定终止条件,startIndex >= s.length(),代表切割到最后一位
- 单层递归,处理节点
class Solution {
List<List<String>> res = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
backTracking(s, 0);
return res;
}
public void backTracking(String s, int startIndex) {
//终止条件
if (startIndex >= s.length()) {
res.add(new ArrayList<>(path));
return;
}
//单层循环
for (int i = startIndex; i < s.length(); i++) {
//操作节点,是回文就加入path
if (isPalindrome(s, startIndex, i)) {
String str = s.substring(startIndex, i+1);
path.add(str);
} else {
continue;
}
//递归
backTracking(s, i + 1);
//回溯
path.remove(path.size() - 1);
}
}
public boolean isPalindrome(String s, int startIndex, int end) {
while (startIndex < end) {
if(s.charAt(startIndex) != s.charAt(end))
return false;
startIndex++;
end--;
}
return true;
}
}