A possible bitwise solution


  • 0
    Y
    class Solution {
        public:
            int totalNQueens(int n);
        private:
            void counting(int column, int ld, int rd);
            int all;
            int ret;
    };
    
    int Solution::totalNQueens(int n) {
        all = (1 << n) - 1;
        ret = 0;
        counting(0, 0, 0);
        return ret;
    }
    
    void Solution::counting(int column, int ld, int rd) {
        if (column == all) {
            ++ ret;
            return;
        }
        int status = all & (~(column | ld | rd));
        while (status != 0) {
            int next = status & (-status);
            status -= next;
            counting(column | next, (ld | next) << 1, (rd | next) >> 1);
        }
    }
    

    A little bit tricky when using bitwise to represent the status.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.