<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p>

<p>Given an integer <code>n</code>, return <em>all distinct solutions to the <strong>n-queens puzzle</strong></em>. You may return the answer in <strong>any order</strong>.</p>

<p>Each solution contains a distinct board configuration of the n-queens&#39; placement, where <code>&#39;Q&#39;</code> and <code>&#39;.&#39;</code> both indicate a queen and an empty space, respectively.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" style="width: 600px; height: 268px;" />
<pre>
<strong>Input:</strong> n = 4
<strong>Output:</strong> [[&quot;.Q..&quot;,&quot;...Q&quot;,&quot;Q...&quot;,&quot;..Q.&quot;],[&quot;..Q.&quot;,&quot;Q...&quot;,&quot;...Q&quot;,&quot;.Q..&quot;]]
<strong>Explanation:</strong> There exist two distinct solutions to the 4-queens puzzle as shown above
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[&quot;Q&quot;]]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 9</code></li>
</ul>

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> ans;
        if (n < 0 || n > 9) return ans;
        
        set<int> cols;
        set<int> posDiag;
        set<int> negDiag;
        vector<string> board;
        for (int k=0;k<n;k++) {
            string s(n, '.');
            board.push_back(s);
        }

        for (int i=0; i<n; i++) {
           backtrack(n, i, cols, posDiag, negDiag, board, ans);
        }
        return ans;
    }

    void backtrack(int n, int row, set<int> &cols, set<int> &posDiag, set<int> &negDiag, vector<string> &board, vector<vector<string>> &ans) {
        if (row == n ) {
            if (cols.size() == n) ans.push_back(board);
            return;
        }
        // backtrack(n, row+1, cols, posDiag, negDiag, board, ans);


        for (int col=0; col<n; col++) {
            if (cols.count(col) || posDiag.count(row+col) || negDiag.count(row-col)) continue;
            board[row][col] = 'Q';
            cols.insert(col);
            posDiag.insert(row+col);
            negDiag.insert(row-col);
            backtrack(n, row+1, cols, posDiag, negDiag, board, ans);

            // reset
            board[row][col] = '.';
            cols.erase(col);
            posDiag.erase(row+col);
            negDiag.erase(row-col);
        }
    }
};
20996