N皇后问题。 没想到数学方法求解,还是按照递归回溯的算了。
public class Solution {
int res=0;
int []use = null;
int []pos = null;
public int totalNQueens(int n) {
if(n==0)
{
return 0;
}
use = new int[n];
// for( int i=0;i<n;i++ )
// {
// use[i] = 0;
// }
pos = new int[n];
fun(0,n);
return res;
}
void fun(int st,int n)
{
if(st==n)
{
res++;
return ;
}
for( int i=0;i<n;i++ )
{
if(use[i]==0&&check(i,st) )
{
use[i]=1;
pos[st]=i;
fun(st+1,n);
use[i]=0;
}
}
}
boolean check(int y,int x)
{
if( x== 0 )
{
return true;
}
for(int i=0;i<x;i++ )
{
if(Math.abs(i-x)==Math.abs(pos[i]-y))
{
return false;
}
}
return true;
}
}