N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Example
For n=4, there are 2 distinct solutions.
Solution:
这道题的区别就是不需要把具体方案打印出来,但是还是需要usedColumns变量来动态的存储方案的情况。
class Solution:
"""
Calculate the total number of distinct N-Queen solutions.
@param n: The number of queens.
@return: The total number of distinct solutions.
"""
def __init__(self):
self.sum = 0
def totalNQueens(self, n):
# write your code here
usedColumns = [0] * n
self.dfs(usedColumns, 0)
return self.sum
def dfs(self, usedColumns, row):
n = len(usedColumns)
if n == row:
self.sum += 1
return
for i in range(n):
if self.isValid(usedColumns, row, i):
usedColumns[row] = i
self.dfs(usedColumns, row + 1)
def isValid(self, usedColumns, row, col):
for i in range(row):
if usedColumns[i] == col:
return False
if row - i == abs(col - usedColumns[i]):
return False
return True回溯法:
Last updated
Was this helpful?