1. Description
Given an integer N, find the number of beautiful arrangements can construct by integers from 1 to N.
We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 <= i <= N) in this array:
- The number at the ith position is divisible by i.
- i is divisible by the number at the ith position.
2. Solution
Backtracking.
Implement an array of boolean to record whether the numbers have been used.
For every position of the array, if one number has never been used and can be placed at the position, then place it.
And try to place other numbers that have not been used.
3. Code
int countArrangement(int N) {
int ans = 0;
bool vis[N+1];
for(int i=0;i<=N;i++)
vis[i]=false;
dfs(N,vis,ans,0);
return ans;
}
void dfs(int n, bool vis[],int& ans,int cnt){
if(n==cnt){
ans++;
return;
}
for(int i=1;i<=n;i++){
if(!vis[i]){
int x = cnt+1;
if(x%i==0||i%x==0){
vis[i]=true;
dfs(n,vis,ans,cnt+1);
vis[i]=false;
}
}
}
}