关键位运算
x & (-x) 取得最低位1
x & (x-1) 去掉最低位1
class Solution(object):
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
if n < 1 : return []
self.count = 0
self.DFS(n,0,0,0,0)
return self.count
def DFS(self,n, row, cols, pie, na):
if row >=n:
self.count += 1
return
# 得到当前所有的空位
bits = (~(cols | pie | na)) & ((1<<n)-1)
while bits:
p = bits & -bits # 取到最低位的1
self.DFS(n, row + 1, cols|p, (pie|p) <<1, (na|p)>>1)
bits = bits & (bits - 1) # 去掉最低位的1
原文地址:https://www.cnblogs.com/yeni/p/11634467.html
时间: 2024-10-08 23:50:06