N-Queens II

Now, instead outputting board configurations, return the total number of distinct solutions.

N-Queens II
 1 public class Solution {
 2     public int totalNQueens(int n) {
 3         int []total = new int [1];
 4         get(new int[n],0,n,total);
 5         return total[0];
 6     }
 7     public void get(int []queenList,int row,int n,int []total){
 8         if(row==n){
 9             total[0]++;
10         }
11         for(int col=0;col<n;col++){
12             if(check(queenList,row,col)){
13                 queenList[row]=col;
14                 get(queenList,row+1,n,total);
15             }
16         }
17     }
18     public boolean check(int[] queenList,int row,int col){
19         for(int preRow=0;preRow<row;preRow++){
20             int preCol = queenList[preRow];
21             if(preCol==col)return false;
22             if(Math.abs(preCol-col)==Math.abs(preRow-row)) return false;
23         }
24         return true;
25     }
26 }
View Code

N-Queens II

上一篇:我的博客我做主


下一篇:Remove Duplicates from Sorted List II