Sharing my 4ms C++ solution


  • 0
    T
    class Solution {
    private:
        bool isValidPosition(vector<int>& positions, int row, int col)
        {
            int n = positions.size(), i;
            for(i=0; i<row; i++)
            {
                if( col==positions[i] || abs(row-i)==abs(col-positions[i]) )
                    return false;
            }
            
            return true;
        }
        
        void totalNQueensHelper(int n, vector<int>& positions, int row, int& result)
        {
            if(row==n)
                return;
                
            int i;
            for(i=0; i<n; i++)
            {
                if(isValidPosition(positions, row, i))
                {
                    if(row==n-1)
                    {
                        result=result+1;
                        break;
                    }
                    else
                    {
                        positions[row]=i;
                        totalNQueensHelper(n, positions, row+1, result);
                    }
                }
            }
        }
        
    public:
        int totalNQueens(int n) {
            vector<int> positions(n);
            int result = 0;
            totalNQueensHelper(n, positions, 0, result);
            return result;
        }
    };

Log in to reply
 

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