LeetCode_N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

  

class Solution {
public:
   bool isValid(int* row, int curRow)
    {
        for(int i = 0; i< curRow; i++)
          if(row[i] == row[curRow] || abs(row[i] - row[curRow]) == curRow - i)
              return false;      
        return true;
    }
    void nqueue(int* row,int curRow)
    {
        if(curRow == n)
        {
            res++;
            return ;
        }
        for(int i = 0; i< n ;i++)
        {
            row[curRow] = i;
            if(isValid(row,curRow))
                   nqueue(row,curRow+1);
        }
    }
    int totalNQueens(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        res = 0;
        if( n < 1 ) return res;
        this->n = n;
        int *row = new int[n];
        nqueue(row, 0);
        return res;
    }
private:
    int n;
    int res;
};
原文地址:https://www.cnblogs.com/graph/p/3226765.html