Combinations where every element appears twice and distance between appearances is equal to the value | C ++ 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 code ; given number
#include <bits/stdc++.h> NEW_LINE using namespace std ; void allCombinationsRec ( vector < int > & arr , int elem , int n ) { if ( elem > n ) { for ( int i : arr ) cout << i << " ▁ " ; cout << endl ; return ; } for ( int i = 0 ; i < 2 * n ; i ++ ) { if ( arr [ i ] == -1 && ( i + elem + 1 ) < 2 * n && arr [ i + elem + 1 ] == -1 ) { arr [ i ] = elem ; arr [ i + elem + 1 ] = elem ; allCombinationsRec ( arr , elem + 1 , n ) ; arr [ i ] = -1 ; arr [ i + elem + 1 ] = -1 ; } } } void allCombinations ( int n ) { vector < int > arr ( 2 * n , -1 ) ; int elem = 1 ; allCombinationsRec ( arr , elem , n ) ; } int main ( ) { int n = 3 ; allCombinations ( n ) ; return 0 ; }