Accepted C++, Beats 86.8%, 4ms, 16 lines


  • 2
    void get_boards(vector<vector<string>>& all_boards, vector<string>& board, int row, int l, int m, int r) {
        if (row==0) all_boards.push_back(board);
        int all_pos = ~(l|m|r);
        for (int i=0; i<board.size(); i++)
            if ((1<<i)&all_pos) {
                board[board.size()-row][i] = 'Q';
                get_boards(all_boards,board,row-1,(l|(1<<i))<<1,m|(1<<i),(r|(1<<i))>>1);
                board[board.size()-row][i] = '.';
            }
    }
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> all_boards;
        vector<string> board(n,string(n,'.'));
        get_boards(all_boards,board,n,0,0,0);
        return all_boards;
    }

Log in to reply
 

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