Given a positive number n, we need to find all the combinations of 2*n elements such that every element from 1 to n appears exactly twice and distance between its appearances is exactly equal to value of the element.
Input : n = 3 Output : 3 1 2 1 3 2 2 3 1 2 1 3 All elements from 1 to 3 appear twice and distance between two appearances is equal to value of the element. Input : n = 4 Output : 4 1 3 1 2 4 3 2 2 3 4 2 1 3 1 4
We can use backtracking to solve this problem. The idea is to all possible combinations for the first element and recursively explore remaining element to check if they will lead to the solution or not. If current configuration doesn’t result in solution, we backtrack. Note that an element k can be placed at position i and (i+k+1) in the output array i >= 0 and (i+k+1) < 2*n.
Note that no combination of element is possible for some value of n like 2, 5, 6 etc.
3 1 2 1 3 2 2 3 1 2 1 3
This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Partition of a set into K subsets with equal sum
- Print all the combinations of a string in lexicographical order
- Print all the permutations of a string without repetition using Collections in Java
- Maze With N doors and 1 Key
- Count number of ways to reach destination in a maze
- Print a given matrix in spiral form using direction tracking method
- Program to generate all possible valid IP addresses from given string | Set 2
- Rat in a Maze Problem when movement in all possible directions is allowed
- Generate all permutations of a string that follow given constraints
- Travelling Salesman Problem implementation using BackTracking
- Find triplet such that number of nodes connecting these triplets is maximum
- Print path from root to all nodes in a Complete Binary Tree
- Generate all the binary strings of N bits
- Java Program to print distinct permutations of a string