[LeetCode]N-Queens II

Follow up for N-Queens problem.

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

思考:同样,满足条件res++即可。

class Solution {

private:

    int res;

public:

    bool check(int *a,int k,int i)

    {

        for(int j=0;j<k;j++)

        {

            if(a[j]==i||abs(a[j]-i)==abs(j-k))

            return false;

        }

        return true;

    }

    void NQueen(int *a,int k,int n)

    {

        for(int i=0;i<n;i++)

        {

            if(check(a,k,i))

            {

                a[k]=i;

                if(k==n-1) res++;

                else NQueen(a,k+1,n);

            }

        }

    }

    int totalNQueens(int n) {

        res=0;

        int *a=new int[n];

        NQueen(a,0,n);

        delete []a;

        return res;

    }

};

  

你可能感兴趣的:(LeetCode)