N皇后
class Solution {
public int totalNQueens ( int n) {
int [ ] ans = new int [ 1 ] ;
int [ ] res = new int [ n] ;
queen ( 0 , n, ans, res) ;
return ans[ 0 ] ;
}
public void queen ( int row, int n, int [ ] ans, int [ ] res) {
if ( row == n) { ans[ 0 ] ++ ; return ; }
for ( int i= 0 ; i< n; i++ ) {
res[ row] = i;
if ( ! judge ( res, row) ) {
queen ( row+ 1 , n, ans, res) ;
}
}
}
public boolean judge ( int [ ] res, int k) {
for ( int i= 0 ; i< k; i++ ) {
if ( res[ i] == res[ k] || Math. abs ( i- k) == Math. abs ( res[ i] - res[ k] ) ) {
return true ;
}
}
return false ;
}
}
class Solution {
int ans = 0 ;
public int totalNQueens ( int n) {
dfs ( n, 0 , 0 , 0 , 0 ) ;
return ans;
}
public void dfs ( int n, int row, int col, int nextL, int nextR) {
if ( row >= n) { ans++ ; return ; }
int bits = ( ~ ( col | nextL | nextR) ) & ( ( 1 << n) - 1 ) ;
while ( bits> 0 ) {
int pick = bits & - bits;
dfs ( n, row+ 1 , col| pick, ( nextL| pick) << 1 , ( nextR| pick) >> 1 ) ;
bits &= bits- 1 ;
}
}
}