Given an integer n, count the number of beautiful arrangements you can construct using integers 1 to n. A beautiful arrangement is one where for every i, either perm[i] is divisible by i or i is divisible by perm[i].
Use backtracking: at each position pos (1-indexed), try placing each unused number. A number k is valid at position pos if k % pos == 0 or pos % k == 0. Use a visited array to track used numbers.
- Maintain a boolean visited[] of size n+1.
- At each position pos from 1 to n, try all numbers 1..n that are not visited.
- Check divisibility condition; if valid, mark visited and recurse to pos+1.
- When pos > n, increment count. Backtrack by unmarking visited.
- Time Complexity: O(k) where k is number of valid arrangements
- Space Complexity: O(N) — visited array + stack