Problem Description
Given an array of distinct positive integers, count the number of permutations such that for every adjacent pair, either the left element is divisible by the right element or vice versa. The answer should be computed modulo 10^9 + 7.
Key Insights
- Use Dynamic Programming with Bitmasking to explore all permutations.
- The state dp[mask][i] represents the number of ways to form a permutation ending at index i using the set of elements indicated by mask.
- Precompute a 2D boolean matrix to quickly check the divisibility condition between any two numbers.
- The small input size (n <= 14) makes a 2^n * n DP feasible.
Space and Time Complexity
Time Complexity: O(n^2 * 2^n) Space Complexity: O(n * 2^n)
Solution
We use Bitmask Dynamic Programming. First, we precompute a matrix valid such that valid[i][j] is true if either nums[i] % nums[j] == 0 or nums[j] % nums[i] == 0. We then initialize a dp table with dimensions (1 << n) x n where each dp[mask][i] holds the number of ways to form a permutation ending with element i using indices in mask. The recurrence extends the current permutation by trying all unused elements that satisfy the special condition with the current last element. Finally, we sum the ways for the full mask over all ending indices and return the result modulo 10^9+7.