1330. Beautiful Arrangement — Bitmask Backtracking

MediumBit ManipulationBitmask DPPermutationBacktracking

Given n distinct positive integers, count the permutations that place them into positions 1 through n such that at every position i the placed value v satisfies v % i == 0 or i % v == 0. The classic Beautiful Arrangement problem is the special case where the values are exactly 1..n.

Input: A JSON object {"nums": [<distinct positive integers>]}.

Output: Return the number of valid arrangements.

Examples

Example 1
Input: {"nums":[1,2]}
Output: 2
Explanation: Both orderings satisfy the divisibility rule -> 2.
Example 2
Input: {"nums":[1,2,3]}
Output: 3
Explanation: The classic n=3 answer is 3.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →