class Solution {private: int queen_num; int total;public: int totalNQueens(int n) { queen_num = n; total = 0; vectorh(n, false); vector v(n, false); vector lx(n * 2 + 1, false); vector rx(n * 2 + 1, false); dfs(0, h, v, lx, rx); return total; } void dfs(int level, vector &h, vector &v, vector &lx, vector &rx) { if (level == queen_num) { total++; return; } int row = level; int col = 0; while (col < queen_num) { if (!h[row] && !v[col] && !lx[row + col] && !rx[row + queen_num - col - 1]) { h[row] = v[col] = lx[row + col] = rx[row + queen_num - col - 1] = true; dfs(level + 1, h, v, lx, rx); h[row] = v[col] = lx[row + col] = rx[row + queen_num - col - 1] = false; } col++; } }};
或许可以用状态压缩?