Print all subsequences of a string | Iterative Method | function to find subsequence ; Check if jth bit in binary is 1 ; If jth bit is 1 , include it in subsequence ; Function to print all subsequences ; map to store subsequence lexicographically by length ; Total number of non - empty subsequence in string is 2 ^ len - 1 ; i = 0 , corresponds to empty subsequence ; Subsequence for binary pattern i ; Storing sub in map ; it . first is length of Subsequence it . second is set < string > ; ii is iterator of type set < string > ; Driver code
function subsequence ( s , binary , len ) { let sub = " " ; for ( let j = 0 ; j < len ; j ++ ) if ( binary & ( 1 << j ) ) sub += s [ j ] ; return sub ; } function possibleSubsequences ( s ) { let sorted_subsequence = new Map ( ) ; let len = s . length ; let limit = Math . pow ( 2 , len ) ; for ( let i = 1 ; i <= limit - 1 ; i ++ ) { let sub = subsequence ( s , i , len ) ; if ( ! sorted_subsequence . has ( sub . length ) ) sorted_subsequence . set ( sub . length , new Set ( ) ) ; sorted_subsequence . get ( sub . length ) . add ( sub ) ; } for ( let it of sorted_subsequence ) { document . write ( " " + it [ 0 ] + " " + " " ) ; for ( let ii of it [ 1 ] ) document . write ( ii + " " ) ; document . write ( " " ) ; } } let s = " " ; possibleSubsequences ( s ) ;