lc 52. N-Queens II
you don't need to record x coordinate or recurrence number. only a one dimension done[] and a set() remain can handle it.
Remember the recursive code in your mind. write the state_recorder in outside function fashion.
class Solution: def __init__(self): self.n=None self.done=None self.remain=None self.ans=0 def collision(self,y): x=len(self.done) for i in range(len(self.done)): if abs(x-i)==abs(y-self.done[i]): return True return False def next(self): if len(self.remain)==0: self.ans+=1 return for j in set(self.remain): if not self.collision(j): self.done.append(j) self.remain.discard(j) self.next() self.done.pop() self.remain.add(j) def totalNQueens(self, n): self.n=n self.done=[] self.remain={i for i in range(n)} self.ans=0 self.next() return self.ans