Suppose we have N integers from 1 to N. We will define a beautiful arrangement as an array that is constructed by these N numbers completely if one of the following is true for the ith position (1 <= i <= N) in this array −
So if the input is 2, then the result will be also 2, as the first beautiful arrangement is [1,2]. Here number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1). Then number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2). The second beautiful arrangement is [2, 1]: Here number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1). Then number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int ans; void solve(vector <bool>& visited, int end, int pos = 1){ if(pos == end + 1){ ans++; return; } for(int i = 1; i <= end; i++){ if(!visited[i] && (pos % i == 0 || i % pos == 0)){ visited[i] = true; solve(visited, end, pos + 1); visited[i] = false; } } } int countArrangement(int N) { ans = 0; vector <bool> visited(N); solve(visited, N); return ans; } }; main(){ Solution ob; cout << (ob.countArrangement(2)); }
2
2