Sunday, January 3, 2021

Beautiful Arrangement

Problem: Suppose you have n integers from 1 to n. A beautiful arrangement is an array that is constructed by these n numbers if one of the following is true for every ith index in this array:

  • The number at the ith position is divisible by i.
  • i is divisible by the number at the ith position.

Return the number of the beautiful arrangements that you can construct with the given integer n.

Example(taken from leetcode):

Input: n = 2
Output: 2
Explanation: 
The first beautiful arrangement is [1, 2]:
Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1).
Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2).
The second beautiful arrangement is [2, 1]:
Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1).
Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.


Approach: This is a classical example of backtracking. Just look at the implementation to understand the approach.


Implementation in C#:

        public static int CountArrangement(int n)

        {

            int countbeautifulArrangements = 0;

            if (n <= 0)

            {

                return countbeautifulArrangements;

            }

            bool[] visited = new bool[n + 1];

            CountArrangement(visited, n, 1, ref countbeautifulArrangements);

            return countbeautifulArrangements;

        }


        private static void CountArrangement(bool[] visited, int n, int valueOrIndex, ref int countArrangements)

        {

            if (valueOrIndex > n)

            {

                ++countArrangements;

                return;

            }

            for (int i = 1; i <= n; ++i)

            {

                if (!visited[i] && (valueOrIndex % i == 0 || i % valueOrIndex == 0))

                {

                    visited[i] = true;

                    CountArrangement(visited, n, valueOrIndex + 1, ref countArrangements);

                    visited[i] = false;

                }

            }

        }


Complexity: O(n!)

No comments:

Post a Comment