Leetcode 526. Beautiful Arrangement
You are given an integer n
. A permutation of the first n
positive integers is considered beautiful if for every i
(1 ≤ i ≤ n), one of the following is true:
i
is divisible by the element at the i-th
position.i-th
position is divisible by i
.Given an integer n
, return the number of the beautiful arrangements that you can construct.
n
?
n
will be an integer such that 1 ≤ n ≤ 15.n
is 1?
{1}
which is trivially beautiful.n
.To solve this problem, we will use a backtracking approach:
n
positive integers.[1, 2, ..., n]
.i
satisfies the beautiful arrangement conditions, i.e., i
is divisible by the element at the i-th
position or the element at the i-th
position is divisible by i
.O(n!)
.O(n)
time.O(n * n!)
.Now, let’s implement the solution.
#include <vector>
class Solution {
public:
int countArrangement(int n) {
if (n < 1) return 0;
std::vector<bool> visited(n + 1, false);
return countArrangementHelper(n, 1, visited);
}
private:
int countArrangementHelper(int n, int pos, std::vector<bool>& visited) {
if (pos > n) {
return 1;
}
int count = 0;
for (int i = 1; i <= n; ++i) {
if (!visited[i] && (i % pos == 0 || pos % i == 0)) {
visited[i] = true;
count += countArrangementHelper(n, pos + 1, visited);
visited[i] = false;
}
}
return count;
}
};
countArrangement
initializes a visited
array to keep track of which numbers have been used.countArrangementHelper
starting from position 1.n
in the current position (pos
), ensuring the beautiful arrangement condition.pos
exceeds n
, it means a valid arrangement has been found, and it returns 1.pos
, the function recurses for the next position.visited
array ensures that each number is used only once per arrangement.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?