Smallest number containing all possible N length permutations using digits 0 to D | Java Program to find the minimum length string consisting of all permutations of length N of D digits ; Initialize hashset 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 hashset ; Call the dfs function on the last d characters ; Base case ; Append '0' n - 1 times ; Call the DFS Function ; Driver Code
import java . io . * ; import java . util . * ; import java . lang . * ; class GeeksforGeeks { static Set < String > visited ; static StringBuilder ans ; public static void dfs ( String curr , int D ) { for ( int x = 0 ; x < D ; ++ x ) { String neighbour = curr + x ; if ( ! visited . contains ( neighbour ) ) { visited . add ( neighbour ) ; dfs ( neighbour . substring ( 1 ) , D ) ; ans . append ( x ) ; } } } public static String reqString ( int N , int D ) { if ( N == 1 && D == 1 ) return "0" ; visited = new HashSet < > ( ) ; ans = new StringBuilder ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < N - 1 ; ++ i ) { sb . append ( "0" ) ; } String start = sb . toString ( ) ; dfs ( start , D ) ; ans . append ( start ) ; return new String ( ans ) ; } public static void main ( String args [ ] ) { int N = 2 ; int D = 2 ; System . out . println ( reqString ( N , D ) ) ; } }