Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Subscribe to see which companies asked this question
class Solution(object):
def check(self, k, j): # check if the kth queen can be put in column j!
for i in range(k):
if self.board[i]==j or abs(k-i)==abs(self.board[i]-j):
return False
return True
def dfs(self, depth):
if depth==self.n: self.res += 1; return
for i in range(self.n):
if self.check(depth,i):
self.board[depth]=i
self.dfs(depth+1)
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
self.res = 0
self.n = n
self.board=[-1 for i in range(n)]
self.dfs(0)
return self.res
与上道题思路一致,不过将三个函数分别作为类的成员函数来写了。上道题成员函数套函数的写法,命名空间有一点问题。