Count number of ways to arrange first N numbers | C ++ implementation of the approach ; Function to return the count of required arrangements ; Create a vector ; Store numbers from 1 to n ; To store the count of ways ; Generate all the permutations using next_permutation in STL ; Initialize flag to true if first element is 1 else false ; Checking if the current permutation satisfies the given conditions ; If the current permutation is invalid then set the flag to false ; If valid arrangement ; Generate the next permutation ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int n ) { vector < int > a ; int i = 1 ; while ( i <= n ) a . push_back ( i ++ ) ; int ways = 0 ; do { bool flag = ( a [ 0 ] == 1 ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( abs ( a [ i ] - a [ i - 1 ] ) > 2 ) flag = 0 ; } if ( flag ) ways ++ ; } while ( next_permutation ( a . begin ( ) , a . end ( ) ) ) ; return ways ; } int main ( ) { int n = 6 ; cout << countWays ( n ) ; return 0 ; }