Find the N | C ++ program to find the N - th lexicographic permutation of string using Factroid method ; Function to calculate nth permutation of string ; Creating an empty stack ; Subtracting 1 from N because the permutations start from 0 in factroid method ; Loop to generate the factroid of the sequence ; Loop to generate nth permutation ; Remove 1 - element in each cycle ; Final answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void string_permutation ( long long int n , string str ) { stack < int > s ; string result ; n = n - 1 ; for ( int i = 1 ; i < str . size ( ) + 1 ; i ++ ) { s . push ( n % i ) ; n = n / i ; } for ( int i = 0 ; i < str . size ( ) ; i ++ ) { int a = s . top ( ) ; result += str [ a ] ; int j ; for ( j = a ; j < str . length ( ) ; j ++ ) str [ j ] = str [ j + 1 ] ; str [ j + 1 ] = ' \0' ; s . pop ( ) ; } cout << result << endl ; } int main ( ) { string str = " abcde " ; long long int n = 11 ; string_permutation ( n , str ) ; return 0 ; }