LeetCode第52题:N皇后2(困难)
题目:给定一个整数 n,返回 n 皇后不同的解决方案的数量。 解法一:根据上一题的解法增加了一个变量。
class Solution {
int rows[ ] ;
int hills[ ] ;
int dales[ ] ;
int n;
List< List< String> > output = new ArrayList ( ) ;
int queens[ ] ;
int ans;
public boolean isNotUnderAttack ( int row, int col) {
int res = rows[ col] + hills[ row - col + 2 * n] + dales[ row + col] ;
return ( res == 0 ) ? true : false ;
}
public void placeQueen ( int row, int col) {
queens[ row] = col;
rows[ col] = 1 ;
hills[ row - col + 2 * n] = 1 ;
dales[ row + col] = 1 ;
}
public void removeQueen ( int row, int col) {
queens[ row] = 0 ;
rows[ col] = 0 ;
hills[ row - col + 2 * n] = 0 ;
dales[ row + col] = 0 ;
}
public void addSolution ( ) {
List< String> solution = new ArrayList < String> ( ) ;
for ( int i = 0 ; i < n; ++ i) {
int col = queens[ i] ;
StringBuilder sb = new StringBuilder ( ) ;
for ( int j = 0 ; j < col; ++ j) sb. append ( "." ) ;
sb. append ( "Q" ) ;
for ( int j = 0 ; j < n - col - 1 ; ++ j) sb. append ( "." ) ;
solution. add ( sb. toString ( ) ) ;
}
output. add ( solution) ;
ans++ ;
}
public void backtrack ( int row) {
for ( int col = 0 ; col < n; col++ ) {
if ( isNotUnderAttack ( row, col) ) {
placeQueen ( row, col) ;
if ( row + 1 == n) addSolution ( ) ;
else backtrack ( row + 1 ) ;
removeQueen ( row, col) ;
}
}
}
public int totalNQueens ( int n) {
this . n = n;
rows = new int [ n] ;
hills = new int [ 4 * n - 1 ] ;
dales = new int [ 2 * n - 1 ] ;
queens = new int [ n] ;
backtrack ( 0 ) ;
return ans;
}
}
class Solution {
public int backtrack ( int row, int hills, int next_row, int dales, int count, int n) {
int columns = ( 1 << n) - 1 ;
if ( row == n)
count++ ;
else {
int free_columns = columns & ~ ( hills | next_row | dales) ;
while ( free_columns != 0 ) {
int curr_column = - free_columns & free_columns;
free_columns ^= curr_column;
count = backtrack ( row + 1 ,
( hills | curr_column) << 1 ,
next_row | curr_column,
( dales | curr_column) >> 1 ,
count, n) ;
}
}
return count;
}
public int totalNQueens ( int n) {
return backtrack ( 0 , 0 , 0 , 0 , 0 , n) ;
}
}
作者:LeetCode
链接:https: / / leetcode- cn. com/ problems/ n- queens- ii/ solution/ nhuang- hou- ii- by- leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。