Smallest number containing all possible N length permutations using digits 0 to D | C ++ Program to find the minimum length string consisting of all permutations of length N of D digits ; Initialize set to see if all the possible permutations are present in the min length string ; To keep min length string ; Generate the required string ; Iterate over all the possible character ; Append to make a new string ; If the new string is not visited ; Add in set ; Call the dfs function on the last d characters ; Base case ; Append '0' n - 1 times ; Call the DFS Function ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; set < string > visited ; string ans ; void dfs ( string curr , int D ) { for ( int x = 0 ; x < D ; ++ x ) { char chr = x + '0' ; string neighbour = curr + chr ; if ( visited . find ( neighbour ) == visited . end ( ) ) { visited . insert ( neighbour ) ; dfs ( neighbour . substr ( 1 ) , D ) ; ans . push_back ( chr ) ; } } } string reqString ( int N , int D ) { if ( N == 1 && D == 1 ) return "0" ; visited . clear ( ) ; ans . clear ( ) ; string start ; for ( int i = 0 ; i < N - 1 ; i ++ ) start . append ( "0" ) ; dfs ( start , D ) ; ans . append ( start ) ; return ans ; } int main ( ) { int N = 2 ; int D = 2 ; cout << reqString ( N , D ) << ' ' ; return 0 ; }