所有的回溯问题都是由三个步骤组成:choose、explore、unchoose
因此对每个问题需要知道:
1.choose what?对于这个问题,我们选择每个字符串
2.how to explore?对于这个问题,我们对剩余的字符串做同样的事情。
3.unchoose 做相反的操作选择
让我们以此问题为例:
1.Define helper(),通常我们需要在回溯问题中使用辅助函数,已接收更多参数
2.parameters:通常我们需要以下参数:
(1)要处理的对象:这个问题是String s
(2)一个起始索引或结束索引,指示正在处理的部分:对于这个问题,我们使用substring来指示起始索引,不使用明显的int型
(3)阶段性步骤结果,记住当前选择choose然后取消选择unchoose:对于这个问题,我们使用List<String> step。
(4)最终的结果,记住最终的结果。通常在我们添加时,我们使用'result.add(new ArrayList <>(step))'而不是'result.add(step)',因为step是引用传递的。
3.Base case:基本案例。定义何时将步骤结果添加到最终结果中以及何时返回。
4.Use for-loop:通常需要一个for循环迭代输入String,以便我们可以选择所有选项
5.Choose:在这个问题中,如果s的子串是回文,我们将它添加到步骤中,这意味着我们选择这个子串。
6.Explore:在这个问题中,我们想对剩余的子串做同样的事情。所以我们递归调用我们的函数。
7.Un-Choose:我们退回,删除所选的子字符串,以尝试其他选项。
public List<List<String>> partition(String s) {
// Backtracking
// Edge case
if(s == null || s.length() == 0) return new ArrayList<>();
List<List<String>> result = new ArrayList<>();
helper(s, new ArrayList<>(), result);
return result;
}
public void helper(String s, List<String> step, List<List<String>> result) {
// Base case
if(s == null || s.length() == 0) {
result.add(new ArrayList<>(step));
return;
}
for(int i = 1; i <= s.length(); i++) {
String temp = s.substring(0, i);
if(!isPalindrome(temp)) continue; // only do backtracking when current string is palindrome
step.add(temp); // choose
helper(s.substring(i, s.length()), step, result); // explore
step.remove(step.size() - 1); // unchoose
}
return;
}
public boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while(left <= right) {
if(s.charAt(left) != s.charAt(right))
return false;
left ++;
right --;
}
return true;
}