Special Permutations Problem
Description
LeetCode Problem 2741.
You are given a 0-indexed integer array nums containing n distinct positive integers. A permutation of nums is called special if:
- For all indexes
0 <= i < n - 1, eithernums[i] % nums[i+1] == 0ornums[i+1] % nums[i] == 0.
Return the total number of special permutations. As the answer could be large, return it modulo 10^9+ 7.
Example 1:
Input: nums = [2,3,6]
Output: 2
Explanation: [3,6,2] and [2,6,3] are the two special permutations of nums.
Example 2:
Input: nums = [1,4,3]
Output: 2
Explanation: [3,1,4] and [4,1,3] are the two special permutations of nums.
Constraints:
2 <= nums.length <= 141 <= nums[i] <= 10^9
Solution
Approach: Bitmask DP
n is at most 14, so a bitmask can record which numbers are already used (bit i set means nums[i] is in the permutation).
Let f[mask][j] be the number of valid orderings of the numbers in mask that end with nums[j]. If mask contains only j, then f[mask][j] = 1. Otherwise, remove j to get prev = mask ^ (1 << j), and add up f[prev][k] over every k in prev where nums[j] and nums[k] divide one another (the code simply loops over all k; entries for k not in prev are 0).
The answer is the sum of f[(1 << n) - 1][j] over all j, modulo 10^9 + 7.
Complexity: O(n^2 * 2^n) time and O(n * 2^n) space.
class Solution:
def specialPerm(self, nums: List[int]) -> int:
mod = 10**9 + 7
n = len(nums)
m = 1 << n
f = [[0] * n for _ in range(m)]
for i in range(1, m):
for j, x in enumerate(nums):
if i >> j & 1:
ii = i ^ (1 << j)
if ii == 0:
f[i][j] = 1
continue
for k, y in enumerate(nums):
if x % y == 0 or y % x == 0:
f[i][j] = (f[i][j] + f[ii][k]) % mod
return sum(f[-1]) % mod