classSolution{ public List<List<String>> solveNQueens(int n) { boolean[][] help = newboolean[3][n*2]; int times = 0; List<List<String>> res = new ArrayList<>(); int[] solutionnum = newint[n]; return backtrack(help,times,n,solutionnum,res); }
private List<List<String>> backtrack(boolean[][] help, int times, int n, int[] solutionnum, List<List<String>> res) { if(times == n){ //if 满足结束条件: List<String> solution = new ArrayList<>(); for (int i = 0; i < n; i++) { solution.add( String.join("", Collections.nCopies(solutionnum[i],".")) + "Q" + String.join("", Collections.nCopies(n-solutionnum[i]-1,"."))); } res.add(solution); //将满足的方法添加到结果中 } for (int i = 0; i < n; i++) { //for 选择 in 选择列表: if (!(help[0][i] || help[1][n+i-times] || help[2][i+times])){ help[0][i] = help[1][n+i-times] = help[2][i+times] = true; //做选择 solutionnum[times] = i; backtrack(help,times+1,n,solutionnum,res); help[0][i] = help[1][n+i-times] = help[2][i+times] = false; //撤销选择 } } return res; } }