题目描述:
使用回溯的方法,position数组表示的是下标表示的行,对应的值是皇后所在位置
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<>();
int position[] = new int[n];
get(n, 0, position, result);
return result;
}
public void get(int n,int posi,int [] position,List<List<String>> result){
if(posi == n){
List<String> temList = new ArrayList<>();
for (int i = 0; i < n; i++) {
StringBuilder sBuilder = new StringBuilder();
for (int j = 0; j < n; j++) {
if(position[i] == j){
sBuilder.append("Q");
}else {
sBuilder.append(".");
}
}
temList.add(sBuilder.toString());
}
result.add(temList);
return;
}
for (int i = 0; i < n; i++) {
position[posi] = i;
if(is(posi,position)){
get(n, posi + 1, position, result);
}
}
}
public boolean is(int row, int position[]){
//判断之前的是否满足条件
for (int i = 0; i < row; i++) {
if(position[row] == position[i] || (Math.abs(position[i] - position[row]) == row - i)){
return false;
}
}
return true;
}
}```