Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
和上题方法一样,使用回溯法。结构基本同样。仅仅须要返回数量。public int totalNQueens(int n) { int[] queenAtCol = new int[n]; int total = getNQueens(0, n, queenAtCol); return total; } public List<String[]> solveNQueens(int n) { List <String[]> list = new ArrayList<String[]>(); return list; } private int getNQueens(int row, int n, int[] queenAtCol) { if (row == n) { return 1; } else { int tempSum = 0; for (int col = 0; col < n; col++) { if (isValid(row,col,queenAtCol)) { queenAtCol[row] = col; tempSum += getNQueens(row + 1, n, queenAtCol); } } return tempSum; } } private boolean isValid(int row, int col,int[] queenAtCol) { //row is valid. //column for (int i = 0; i < row; i++) { if (queenAtCol[i] == col) { return false; } } for (int i = 0; i < row; i++) { if (i + queenAtCol[i] == row + col) { return false; } } for (int i = 0; i < row; i++) { if (col - row == queenAtCol[i] - i) { return false; } } return true; }