- Related Questions & Answers
- Beautiful Arrangement II in C++
- Beautiful Array in C++
- Maximum height of triangular arrangement of array values in C++
- Program for printing array in Pendulum Arrangement.
- How to look beautiful in 15 days?
- How to look beautiful without makeup?
- Find if neat arrangement of cups and shelves can be made in C++
- Check if the array is beautiful in Python
- What are the beautiful untranslatable Hindi words?
- How to create beautiful and useful infographics
- What is the most beautiful thing in the world?
- Which country has the most beautiful women in the world?
- who are the top ten most beautiful women in the world?
- How can I enhance my skin tone to look beautiful?
- People look beautiful and graceful with age. Do you agree?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

- The number at the ith position is can be divided by i.
- i is divisible by the number at the ith position.

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 −

- Define a recursive method solve(), that will take visited array, end and pos. The pos is initially 1.
- if pos = end + 1, then increase ans by 1 and return
- for i in range 1 to end
- if i is not visited and pos is divisible by 0 or i is divisible by 0, then
- mark i as visited
- solve(visited, end, pos + 1)
- mark i as unvisited

- if i is not visited and pos is divisible by 0 or i is divisible by 0, then
- from the main method, do the following −
- ans := 0, make an array called visited
- call solve(visited, N, 1)r
- return ans.

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

Advertisements