Combinations where every element appears twice and distance between appearances is equal to the value | Java program to find all combinations where every element appears twice and distance between appearances is equal to the value ; Find all combinations that satisfies given constraints ; if all elements are filled , print the solution ; try all possible combinations for element elem ; if position i and ( i + elem + 1 ) are not occupied in the vector ; place elem at position i and ( i + elem + 1 ) ; recurse for next element ; backtrack ( remove elem from position i and ( i + elem + 1 ) ) ; create a vector of double the size of given number with ; all its elements initialized by 1 ; start from element 1 ; Driver method ; given number
import java . util . Vector ; class Test { static void allCombinationsRec ( Vector < Integer > arr , int elem , int n ) { if ( elem > n ) { for ( int i : arr ) System . out . print ( i + " ▁ " ) ; System . out . println ( ) ; return ; } for ( int i = 0 ; i < 2 * n ; i ++ ) { if ( arr . get ( i ) == - 1 && ( i + elem + 1 ) < 2 * n && arr . get ( i + elem + 1 ) == - 1 ) { arr . set ( i , elem ) ; arr . set ( i + elem + 1 , elem ) ; allCombinationsRec ( arr , elem + 1 , n ) ; arr . set ( i , - 1 ) ; arr . set ( i + elem + 1 , - 1 ) ; } } } static void allCombinations ( int n ) { Vector < Integer > arr = new Vector < > ( ) ; for ( int i = 0 ; i < 2 * n ; i ++ ) { arr . add ( - 1 ) ; } int elem = 1 ; allCombinationsRec ( arr , elem , n ) ; } public static void main ( String [ ] args ) { int n = 3 ; allCombinations ( n ) ; } }