题目:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Example
For n=4, there are 2 distinct solutions.
题解:
Solution 1 ()
class Solution { public: void dfs(int &res, int n, vector<int>& pos, int row) { if(row >= n) { ++res; return; } for(int col=0; col<n; ++col) { if (!isValid(pos, row, col)) { continue; } pos[row] = col; dfs(res, n, pos, row + 1); pos[row] = -1; } } bool isValid(vector<int>& pos, int row, int col) { for (int i = 0; i < row; ++i) { if (pos[i] == col || abs(row - i) == abs(col - pos[i])) { return false; } } return true; } int totalNQueens(int n) { int res = 0; vector<int> pos(n, -1); dfs(res, n, pos, 0); return res; } };