解决回溯问题,需要考虑三个问题:1、路径:已经做出的选择。2、选择列表:你可以做出的选择。3、结束条件。
模板如下:
List<类型> result = new ArrayList<>();
dfs(选择){
if 满足结束条件
result.add(路径)
for(选择列表做选择){
做选择
dfs(往下遍历)
撤销选择
}
}
leetcode52题
//正斜线i - j
Set<Integer> positive = new HashSet<>();
//副斜线i + j
Set<Integer> negative = new HashSet<>();
//当前列
Set<Integer> column = new HashSet<>();
int result = 0;
public int totalNQueens(int n) {
backtrack(n,0);
return result;
}
public void backtrack(int n, int i){
if(i == n){
result++;
return ;
}
for(int j = 0; j < n ; j++){
if(positive.contains(j) || negative.contains(j) || column.contains(j))
continue;
//做选择
column.add(j);
positive.add(i - j);
negative.add(i + j);
//进入下层决策树
backtrack(n,i+1);
//撤销选择
column.remove(j);
positive.remove(i - j);
negative.remove(i + j);
}
}