788. Beautiful Arrangement — Count with First Value Fixed

MediumRecursionRecursion

A 'beautiful arrangement' of integers 1..n is a permutation where for every position i (1-indexed), either perm[i] is divisible by i, or i is divisible by perm[i]. Given two integers n and v (1 <= v <= n), count the number of beautiful arrangements where position 1 is fixed to value v. If v > n or v < 1, return 0. Implement with recursive backtracking (bitmask DP is recommended for efficiency).

Input: Two integers n and v separated by a comma.

Output: Return an integer count.

Examples

Example 1
Input: 2, 1
Output: 1
Explanation: [1,2] is the only arrangement starting with 1.
Example 2
Input: 2, 2
Output: 1
Explanation: [2,1] is the only arrangement starting with 2.
Example 3
Input: 6, 3
Output: 7
Explanation: With n=6 and pos1=3, there are 7 valid completions.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →