To count all special permutations, we use dynamic programming with bitmasking. At each step, we keep track of which numbers have been used and the last number added to the permutation. For each unused number, we check if it can be placed next to the last number according to the divisibility condition. This approach efficiently explores all valid permutations without generating them explicitly.
Use a DP table where dp[mask][last] is the number of ways to build a permutation using the subset ‘mask’ ending with index ’last’.
Initialize dp[1 « i][i] = 1 for all i (starting permutations with each number).
For each mask and last, try to add every unused number ’next’. If nums[last] % nums[next] == 0 or nums[next] % nums[last] == 0, update dp[mask | (1 « next)][next].
Sum all dp[full_mask][i] for all i to get the answer.
classSolution {
public:int specialPerm(vector<int>& nums) {
int n = nums.size(), mod =1e9+7;
vector<vector<int>> dp(1<<n, vector<int>(n));
for (int i =0; i < n; ++i) dp[1<<i][i] =1;
for (int mask =0; mask < (1<<n); ++mask) {
for (int last =0; last < n; ++last) {
if (!(mask & (1<<last))) continue;
for (int next =0; next < n; ++next) {
if (mask & (1<<next)) continue;
if (nums[last] % nums[next] ==0|| nums[next] % nums[last] ==0) {
dp[mask | (1<<next)][next] = (dp[mask | (1<<next)][next] + dp[mask][last]) % mod;
}
}
}
}
int ans =0;
for (int i =0; i < n; ++i) ans = (ans + dp[(1<<n)-1][i]) % mod;
return ans;
}
};
classSolution {
funspecialPerm(nums: IntArray): Int {
val n = nums.size
val mod = 1_000_000_007
val dp = Array(1 shl n) { IntArray(n) }
for (i in0 until n) dp[1 shl i][i] = 1for (mask in0 until (1 shl n)) {
for (last in0 until n) {
if (mask and (1 shl last) ==0) continuefor (next in0 until n) {
if (mask and (1 shl next) !=0) continueif (nums[last] % nums[next] ==0|| nums[next] % nums[last] ==0) {
dp[mask or (1 shl next)][next] = (dp[mask or (1 shl next)][next] + dp[mask][last]) % mod
}
}
}
}
var ans = 0for (i in0 until n) ans = (ans + dp[(1 shl n) - 1][i]) % mod
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defspecialPerm(self, nums: list[int]) -> int:
n, mod = len(nums), 10**9+7 dp = [[0]*n for _ in range(1<<n)]
for i in range(n):
dp[1<<i][i] =1for mask in range(1<<n):
for last in range(n):
ifnot (mask & (1<<last)):
continuefor nxt in range(n):
if mask & (1<<nxt): continueif nums[last] % nums[nxt] ==0or nums[nxt] % nums[last] ==0:
dp[mask|(1<<nxt)][nxt] = (dp[mask|(1<<nxt)][nxt] + dp[mask][last]) % mod
return sum(dp[(1<<n)-1][i] for i in range(n)) % mod