classSolution: defcountArrangement(self, n: int) -> int: self.num = 0 mat = defaultdict(list) for i in range(1, n + 1): for j in range(1, n + 1): if i % j == 0or j % i == 0: mat[i].append(j)
defrecur(k): if k == n + 1: self.num += 1 return for i in mat[k]: if i notin v: v.add(i) recur(k + 1) v.remove(i) v = set() recur(1) return self.num
classSolution: defcountArrangement(self, n: int) -> int: mask = 1 << n f = [0for _ in range(mask)] f[0] = 1 for state in range(mask): cnt = Counter(str(bin(state)))['1'] for i in range(1, n + 1): if (state & (1 << (i-1))) == 0: continue if cnt == 0: continue if i % cnt != 0and cnt % i != 0: continue f[state] += f[state & (~(1 << (i-1)))] return f[mask-1]