Print all the combinations of a string in lexicographical order | function to print string ; Method to found all combination of string it is based in tree ; return if level is equal size of string ; if occurrence of char is 0 then skip the iteration of loop ; decrease the char occurrence by 1 ; store the char in result ; print the string till level ; call the function from level + 1 ; backtracking ; declare the map for store each char with occurrence ; initialize the input array with all unique char ; initialize the count array with occurrence the unique char ; temporary char array for store the result ; store the element of input array ; store the element of count array ; size of map ( no of unique char ) ; size of original string ; call function for print string combination ; Driver code
function printResult ( result , len ) { for ( var i = 0 ; i <= len ; i ++ ) document . write ( result [ i ] ) ; document . write ( " " ) ; } function stringCombination ( result , str , count , level , size , len ) { if ( level === size ) return ; for ( var i = 0 ; i < len ; i ++ ) { if ( count [ i ] === 0 ) continue ; count [ i ] -- ; result [ level ] = str [ i ] ; printResult ( result , level ) ; stringCombination ( result , str , count , level + 1 , size , len ) ; count [ i ] ++ ; } } function combination ( str ) { var i ; var mp = { } ; for ( i = 0 ; i < str . length ; i ++ ) if ( mp . hasOwnProperty ( str [ i ] ) ) mp [ str [ i ] ] = mp [ str [ i ] ] + 1 ; else mp [ str [ i ] ] = 1 ; var input = new Array ( Object . keys ( mp ) . length ) . fill ( 0 ) ; var count = new Array ( Object . keys ( mp ) . length ) . fill ( 0 ) ; var result = new Array ( str . length ) . fill ( 0 ) ; i = 0 ; for ( const [ key , value ] of Object . entries ( mp ) ) { input [ i ] = key ; count [ i ] = value ; i ++ ; } var len = Object . keys ( mp ) . length ; var size = str . length ; stringCombination ( result , input , count , 0 , size , len ) ; } var str = " " ; combination ( str ) ;