How can I improve my code?


  • 0
    T

    Here is my c++ solution. It takes 4 ms.

    class Solution {
    public:
        int totalNQueens(int n) {
            this->count = 0;
            this->columns = vector<int>(n, 0);
            this->lines1 = vector<int>(2*n, 0);
            this->lines2 = vector<int>(2*n, 0);
            vector<int> rows(n, 0);
            
            ResolveNQueens(rows, 0);
            return this->count;
        }
    
    private:
        vector<int> columns;
        vector<int> lines1;
        vector<int> lines2;
        int count;
        
        void ResolveNQueens(vector<int> &rows, int row)
        {
            if(row == rows.size())
            {
                this->count++;
                return;
            }
            
            for(int i=0; i<rows.size(); i++)
            {
                if(this->columns[i] == 0
                    &&this->lines1[row+i] == 0
                    &&this->lines2[rows.size()-row+i] == 0)
                {
                    rows[row] = i;
                    this->columns[i] = 1;
                    this->lines1[row+i] = 1;
                    this->lines2[rows.size()-row+i] = 1;
                    
                    ResolveNQueens(rows, row+1);
                    
                    rows[row] = 0;
                    this->columns[i] = 0;
                    this->lines1[row+i] = 0;
                    this->lines2[rows.size()-row+i] = 0;
                }
            }
        }
    };

Log in to reply
 

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