leetcode专题训练 52. N-Queens II

和上一道题没什么差别,把output改成数字就可以了。这时候需要注意下作用域问题,如果output在BackTrack函数外定义,且不是list,那么就不能传到内嵌函数里。

class Solution:
    def totalNQueens(self, n: int) -> int:
        if n == 1:
            return 1
        
        def BackTrack(now = 0, output = 0):
            if now == n:
                output += 1
                return output
            for i in range(n):
                if col[i] or h[now+i] or s[now-i+n-1]:
                    continue
                col[i] = 1
                h[now+i] = 1
                s[now-i+n-1] = 1
                tmp[now][i] = 'Q'
                output = BackTrack(now+1, output)
                col[i] = 0
                h[now+i] = 0
                s[now-i+n-1] = 0
                tmp[now][i] = '.'
            return output
                
        tmp = [['.' for i in range(n)] for i in range(n)]
        col = [0]*n
        h = [0]*(n*2-1)
        s = [0]*(n*2-1)
        output = BackTrack()
        return output

你可能感兴趣的:(leetcode)