Classic recursion\pruning problem. We can use O(n) space: A[i] = j means [i,j] is occupied.
class Solution { public: int ret; bool isValid(int *A, int r) { for (int i = 0; i < r; i++) if ((abs(A[i] - A[r]) == abs(i - r) || A[i] == A[r])) return false; return true; } void go(int *A, int r, int n) { if (r == n) { ret++; return; } for (int i = 0; i < n; i++) { A[r] = i; if (isValid(A, r)) go(A, r + 1, n); } } int totalNQueens(int n) { ret = 0; int *A = new int[n]; go(A, 0, n); delete[] A; return ret; } };
LeetCode "N-Queens II",布布扣,bubuko.com
原文:http://www.cnblogs.com/tonix/p/3857663.html