Question Link
https://leetcode.com/problems/n-queens-ii/
Question Description
Give a nn size of board, return number of distinct solutions to the n-queens.
Input: n = 4
Output: 2
*Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Simulation
Implementation
int res = 0;public int totalNQueens(int n) {//List < List < String >> ret = new ArrayList < > ();char[][] chessBoard = new char[n][n];for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {chessBoard[i][j] = '.';}}boolean[] col = new boolean[n];boolean[] diag1 = new boolean[2 * n - 1];boolean[] diag2 = new boolean[2 * n - 1];backTracking(chessBoard, 0, n, col, diag1, diag2);return res;}private void backTracking(char[][] curr, int idx, int n, boolean[] col, boolean[] diag1, boolean[] diag2) {if (idx == n) {res++;return;}for (int j = 0; j < n; j++) {if (col[j] || diag1[idx + n - j - 1] || diag2[idx + j]) {continue;}col[j] = true;diag1[idx + n - j - 1] = true;diag2[idx + j] = true;curr[idx][j] = 'Q';backTracking(curr, idx + 1, n, col, diag1, diag2);curr[idx][j] = '.';col[j] = false;diag1[idx + n - j - 1] = false;diag2[idx + j] = false;}}
