Leetcode 526. Beautiful Arrangement
The problem is defined as follows:
Suppose you have n
integers from 1
to n
. We define a “beautiful arrangement” as an arrangement where for every i-th
position 1 <= i <= n
, either of the following is true:
i-th
position is divisible by i
.i
is divisible by the number at the i-th
position.Given an integer n
, return the count of the beautiful arrangements that you can form.
n
?n
be negative or zero?Response: Assume n
is a positive integer and 1 <= n <= 15
.
n
?Response: Yes, the output should be the count of beautiful arrangements.
To solve this problem, we can use backtracking to generate all possible permutations of the integers from 1
to n
and count the permutations that satisfy the problem’s conditions.
1
to n
in positions 1
to n
.Here is the Java code implementing the above strategy:
public class Solution {
private int count = 0;
public int countArrangement(int n) {
boolean[] visited = new boolean[n + 1];
backtrack(1, n, visited);
return count;
}
private void backtrack(int position, int n, boolean[] visited) {
if (position > n) {
count++;
return;
}
for (int i = 1; i <= n; i++) {
if (!visited[i] && (i % position == 0 || position % i == 0)) {
visited[i] = true;
backtrack(position + 1, n, visited);
visited[i] = false;
}
}
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.countArrangement(2)); // Output: 2
}
}
n
numbers. In the worst case, this is O(n!)
where n
is the number of integers.O(n)
time. Hence the overall time complexity is O(n! * n)
for large n
.visited
array.n
and the visited
array takes O(n)
space.O(n)
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?