Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Recursion & Backtracking

Beautiful Arrangements

Medium · Recursion & Backtracking · Asked at Google, Amazon, Microsoft

A permutation p of 1 … n (positions are 1-based) is beautiful if for every position i, either p[i] is divisible by i or i is divisible by p[i]. Print the number of beautiful permutations.

Input

A single integer n.

Output

The number of beautiful arrangements.

Constraints

Fill positions from n down to 1 (the hardest positions first), trying only unused numbers that satisfy the rule — pruning keeps it fast. A bitmask DP over used numbers, O(n · 2^n), also works.

Example 1

Input

2

Output

2

Example 2

Input

1

Output

1

Hints

  1. Plain backtracking over all n! permutations is too slow for n = 15 without pruning.
  2. Which numbers are already used matters, not their order — that is a bitmask.
  3. The next position to fill is popcount(mask) + 1.

Approach

dp[mask] = number of ways to fill positions 1 … popcount(mask) using exactly the numbers in mask, all satisfying the rule. From each mask with pos = popcount(mask) + 1, try every unused v with v % pos == 0 or pos % v == 0 and add dp[mask] to dp[mask | bit(v)]. dp[all] is the answer. 2^15 masks × 15 numbers ≈ 5 × 10^5 steps.

Complexity: O(n · 2^n) time · O(2^n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<long long> dp(1 << n, 0);
    dp[0] = 1;
    for (int mask = 0; mask < (1 << n); mask++) {
        if (!dp[mask]) continue;
        int pos = __builtin_popcount(mask) + 1;
        for (int v = 1; v <= n; v++)
            if (!(mask & (1 << (v - 1))) && (v % pos == 0 || pos % v == 0)) dp[mask | (1 << (v - 1))] += dp[mask];
    }
    cout << dp[(1 << n) - 1] << "\n";
    return 0;
}

Python solution

n = int(input())
dp = [0] * (1 << n)
dp[0] = 1
for mask in range(1 << n):
    ways = dp[mask]
    if not ways:
        continue
    pos = bin(mask).count("1") + 1
    for v in range(1, n + 1):
        bit = 1 << (v - 1)
        if not mask & bit and (v % pos == 0 or pos % v == 0):
            dp[mask | bit] += ways
print(dp[(1 << n) - 1])

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();
        long[] dp = new long[1 << n];
        dp[0] = 1;
        for (int mask = 0; mask < (1 << n); mask++) {
            if (dp[mask] == 0) continue;
            int pos = Integer.bitCount(mask) + 1;
            for (int v = 1; v <= n; v++)
                if ((mask & (1 << (v - 1))) == 0 && (v % pos == 0 || pos % v == 0)) dp[mask | (1 << (v - 1))] += dp[mask];
        }
        System.out.println(dp[(1 << n) - 1]);
    }
}

Solve Beautiful Arrangements online · All practice problems