Number of Self-Divisible Permutations Problem
Description
LeetCode Problem 2992.
Given an integer n, return the number of permutations of the 1-indexed array nums = [1, 2, ..., n], such that it's self-divisible.
A 1-indexed array a of length n is self-divisible if for every 1 <= i <= n, gcd(a[i], i) == 1.
A permutation of an array is a rearrangement of the elements of that array, for example here are all of the permutations of the array [1, 2, 3]:
[1, 2, 3][1, 3, 2][2, 1, 3][2, 3, 1][3, 1, 2][3, 2, 1]
Example 1:
Input: n = 1
Output: 1
Explanation: The array [1] has only 1 permutation which is self-divisible.
Example 2:
Input: n = 2
Output: 1
Explanation: The array [1,2] has 2 permutations and only one of them is self-divisible:
nums = [1,2]: This is not self-divisible since gcd(nums[2], 2) != 1.
nums = [2,1]: This is self-divisible since gcd(nums[1], 1) == 1 and gcd(nums[2], 2) == 1.
Example 3:
Input: n = 3
Output: 3
Explanation: The array [1,2,3] has 3 self-divisble permutations: [1,3,2], [3,1,2], [2,3,1].
It can be shown that the other 3 permutations are not self-divisible. Hence the answer is 3.
Constraints:
1 <= n <= 12
Solution
Approach: Bitmask DP
Build the permutation position by position. A bitmask records which values are already used; its number of set bits tells us which position i we fill next. Value j can go there if it is unused and gcd(i, j) == 1 (the position and the value must be coprime).
dfs(mask) returns the number of ways to finish the permutation from this state: it is 1 when all positions are filled, otherwise the sum of dfs(mask | 1 << j) over valid j. Memoize on mask.
Complexity: O(n * 2n) time and O(2n) space.
from functools import lru_cache
from math import gcd
class Solution:
def selfDivisiblePermutationCount(self, n: int) -> int:
@lru_cache(None)
def dfs(mask: int) -> int:
i = bin(mask).count('1') + 1
if i > n:
return 1
ans = 0
for j in range(1, n + 1):
if (mask >> j & 1) == 0 and gcd(i, j) == 1:
ans += dfs(mask | 1 << j)
return ans
return dfs(0)