leetcode n后问题

I:

传统n后问题

class Solution {
public:
vector<string>v1;
vector<vector<string>>v;
vector<int>x;
    vector<vector<string> > solveNQueens(int n) 
    {
        x.clear();
        for(int i=0;i<n;i++)
        x.push_back(0);
        v.clear();
        dfs(0,n);
        return v;      
    }
    void dfs(int depth,int n)
    {
        if(depth==n)
        {
            v1.clear();
            for(int j=0;j<n;j++)
            {
                string s1;
                for(int k=0;k<x[j];k++)
                s1+=".";
                s1+="Q";
                for(int k=x[j]+1;k<n;k++)
                s1+=".";                
                v1.push_back(s1);
            }
            v.push_back(v1);
        }
        else 
        {
            for(int i=0;i<n;i++)
            {
                x[depth]=i;
                if(check(depth))dfs(depth+1,n);
            }
        }
    }
    bool check(int depth)
    {
        for(int i=0;i<depth;i++)
        {
            int diff=abs(x[depth]-x[i]);
            if(diff==0||diff==depth-i)
            return false;
        }
        return true;
    }    
};

 II:

输出解的数量

class Solution {
public:
int sum;
vector<int>x;
    int totalNQueens(int n) 
    { 
        x.resize(n);
        sum=0;
        dfs(0,n);
        return sum;
    }
    void dfs(int depth,int n)
    {
        if(depth==n)
        {
            sum++;
        }
        else 
        {
            for(int i=0;i<n;i++)
            {
                x[depth]=i;
                if(check(depth))dfs(depth+1,n);
            }
        }
    }
    bool check(int depth)
    {
        for(int i=0;i<depth;i++)
        {
            int diff=abs(x[depth]-x[i]);
            if(diff==0||diff==depth-i)
            return false;
        }
        return true;
    }   
};
原文地址:https://www.cnblogs.com/tgkx1054/p/3101839.html