052 N Queens 2
纯递归方法, 网上有一个bit manipulation 的方法 不(看)想(不)深(大)究(懂) LOL
class Solution: def __init__(self): self.ans = 0 # @param {integer} n # @return {integer} def totalNQueens(self, n): self.helper(0,[[0]* n for i in range(0,n)],n) return self.ans def helper(self, level, tmp, n): if level == n: self.ans += 1 return for pos in range(0,n): flag = True for i in range(0, level): if not flag: break if tmp[i][pos] == 1: flag = False break for j in range(0, n): if tmp[i][j]== 1 and (level-i == pos-j or level-i==j-pos): flag = False break if flag: tmp[level][pos] = 1 self.helper(level+1, tmp, n) tmp[level][pos] = 0