My simple c++ solution


  • 0
    K
    class Solution {
    public:
    bool valid(vector<int>columns, int rows, int col)
    {
        for(int prev=0; prev<rows; prev++)
        {
            int queen=columns[prev];
            if(col==queen)return false;
            if(abs(rows-prev) == abs(col-queen))return false;
        }
    
        return true;
    
    }
    
    void helper(int rows, vector<int>&columns, int n, int & count)
    {
        int col;
        if(rows==n)count++;
        else 
        {
            for(col=0; col<n; col++)
            {
                if(valid(columns, rows, col))
                {
                    columns[rows] = col;
                    helper(rows+1, columns, n, count);
                }
            }   
        }
    }
    int totalNQueens(int n) {
        int count=0;
        vector<int>columns(n);
        helper(0, columns, n, count);
        return count;
    }
    

    };


Log in to reply
 

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