Input: n =1Output: 1Explanation: The array [1] has only 1 permutation which is self-divisible.
Example 2:
1
2
3
4
5
Input: n =2Output: 1Explanation: 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:
1
2
3
4
Input: n =3Output: 3Explanation: 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 is3.
We need to count all permutations of [1..n] such that for every position i (1-indexed), gcd(a[i], i) == 1. Since n is small (≤12), we can use backtracking with a bitmask to efficiently try all possible assignments.
#include<numeric>classSolution {
public:int countSelfDivisiblePermutations(int n) {
int ans =0;
function<void(int,int)> dfs = [&](int i, int mask) {
if (i > n) { ++ans; return; }
for (int x =1; x <= n; ++x) {
if (!(mask & (1<<(x-1))) && gcd(x,i)==1) {
dfs(i+1, mask|(1<<(x-1)));
}
}
};
dfs(1, 0);
return ans;
}
intgcd(int a, int b) { return b ? gcd(b, a%b) : a; }
};
funccountSelfDivisiblePermutations(nint) int {
varansintvargcdfunc(a, bint) intgcd = func(a, bint) int {
forb!=0 {
a, b = b, a%b }
returna }
vardfsfunc(i, maskint)
dfs = func(i, maskint) {
ifi > n {
ans++return }
forx:=1; x<=n; x++ {
ifmask&(1<<(x-1)) ==0&&gcd(x,i) ==1 {
dfs(i+1, mask|(1<<(x-1)))
}
}
}
dfs(1, 0)
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
publicintcountSelfDivisiblePermutations(int n) {
return dfs(n, 1, 0);
}
intdfs(int n, int i, int mask) {
if (i > n) return 1;
int ans = 0;
for (int x = 1; x <= n; ++x) {
if ((mask & (1<<(x-1))) == 0 && gcd(x,i) == 1) {
ans += dfs(n, i+1, mask|(1<<(x-1)));
}
}
return ans;
}
intgcd(int a, int b) {
return b == 0 ? a : gcd(b, a%b);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funcountSelfDivisiblePermutations(n: Int): Int {
fungcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a % b)
var ans = 0fundfs(i: Int, mask: Int) {
if (i > n) { ans++; return }
for (x in1..n) {
if ((mask and (1 shl (x-1))) ==0&& gcd(x,i) ==1) {
dfs(i+1, mask or (1 shl (x-1)))
}
}
}
dfs(1, 0)
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from math import gcd
classSolution:
defcountSelfDivisiblePermutations(self, n: int) -> int:
ans =0defdfs(i: int, mask: int):
nonlocal ans
if i > n:
ans +=1returnfor x in range(1, n+1):
ifnot (mask & (1<<(x-1))) and gcd(x,i) ==1:
dfs(i+1, mask|(1<<(x-1)))
dfs(1, 0)
return ans
impl Solution {
pubfncount_self_divisible_permutations(n: i32) -> i32 {
fngcd(mut a: i32, mut b: i32) -> i32 {
while b !=0 {
let t = b;
b = a % b;
a = t;
}
a
}
fndfs(n: i32, i: i32, mask: i32) -> i32 {
if i > n { return1; }
letmut ans =0;
for x in1..=n {
if (mask & (1<<(x-1))) ==0&& gcd(x,i) ==1 {
ans += dfs(n, i+1, mask|(1<<(x-1)));
}
}
ans
}
dfs(n, 1, 0)
}
}