LeetCode||52. N-Queens II

来源:互联网 发布:php 淘宝csv导入源码 编辑:程序博客网 时间:2024/06/03 09:06

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

这题比上一题简化一点,不用拍列出所有的情况,只要给个数字,思路还是回溯

class Solution(object):    def totalNQueens(self, n):        """        :type n: int        :rtype: int        """        def isqueens(depth, val):        for i in range(depth):        if board[i] == val or abs(depth-i) == abs(board[i]-val):        return False        return True        def dfs(depth):        if depth == n:        ans.append(0)        return        for i in range(n):        if isqueens(depth, i):        board[depth] = i        dfs(depth+1)        board = [-1 for i in range(n)]        ans = []        dfs(0)        return len(ans)


原创粉丝点击