框架,相当于一颗树(决策树),每个节点对应一个选择(合理答案),记录路径
result = []
def backtrack(路径, 选择列表):
if 满足结束条件:
result.add(路径)
return
for 选择 in 选择列表:
做选择
backtrack(路径, 选择列表)
撤销选择
常见题目
1.请你写一个算法,输入是一个正整数
n
,输出是n
对儿括号的所有合法组合
import java.util.ArrayList;
import java.util.List;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
if (n == 0) {
return result;
}
//记录路径
StringBuilder track = new StringBuilder();
backtrack(n, n, track, result);
return result;
}
public void backtrack(int left, int right, StringBuilder track, List result) {
//左括号大于右括号
if (left > right) {
return;
}
if (left < 0 || right < 0) {
return;
}
//结束(注意是&&,当左括号右括号都为零的时候)
if (left == 0 && right == 0) {
result.add(track.toString());
return;
}
//尝试加入“(”
track.append('(');
backtrack(left - 1, right, track, result);
track.deleteCharAt(track.length() - 1);
//尝试加入“)”
track.append(')');
backtrack(left, right - 1, track, result);
track.deleteCharAt(track.length() - 1);
}
}
//leetcode submit region end(Prohibit modification and deletion)