[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;
    }
};

  

posted @ 2014-01-12 13:38  七年之后  阅读(197)  评论(0编辑  收藏  举报