class Solution {
public:
    int res = 0, N;
    int column = 0, diagonal1 = 0, diagonal2 = 0;
    //使用集合时替换成 unordered_set<int> column, diagonal1, diagonal2;
    int Nqueen(int n) {
        N = n;
        helper(0);
        return res;
    }
    void helper(int n) {
        if(n == N) {
            res++;
            return;
        }
        for(int i = 0; i < N; i++) {
            int temp1 = i + n, temp2 = N + n - i;
            if(!bit_value(column, i) && !bit_value(diagonal1, temp1) && !bit_value(diagonal2, temp2)) {
                change_bit_value(column, i, 1);
                change_bit_value(diagonal1, temp1, 1);
                change_bit_value(diagonal2, temp2, 1);
                helper(n + 1);
                change_bit_value(column, i, 0);
                change_bit_value(diagonal1, temp1, 0);
                change_bit_value(diagonal2, temp2, 0);
            }
            /*使用集合时替换成
            if(!column.count(i) && !diagonal1.count(temp1) && !diagonal2.count(temp2)) {
                column.insert(i);
                diagonal1.insert(temp1);
                diagonal2.insert(temp2);
                helper(n + 1);
                column.erase(i);
                diagonal1.erase(temp1);
                diagonal2.erase(temp2);
            } */
        }
    }
    int bit_value(int &num, int n) {
        return (num >> n) & 1;
    }
    void change_bit_value(int &num, int n, int value) {
        if(value == 1) num |= (1 << n);
        else num &= ~(1 << n);
    }
};