Printing all subsets of { 1 , 2 , 3 , ... n } without using array or loop | This recursive function calls subset function to print the subsets one by one . numBits -- > number of bits needed to represent the number ( simply input value n ) . num -- > Initially equal to 2 ^ n - 1 and decreases by 1 every recursion until 0. ; Print the subset corresponding to binary representation of num . ; Call the function recursively to print the next subset . ; This function recursively prints the subset corresponding to the binary representation of num . nthBit -- > nth bit from right side starting from n and decreases until 0 ; Print number in given subset only if the bit corresponding to it is set in num . ; Check for the next bit ; Driver Code
function printSubsets ( numOfBits , num ) { if ( num >= 0 ) { document . write ( " " ) ; subset ( numOfBits - 1 , num , numOfBits ) ; document . write ( " " ) ; printSubsets ( numOfBits , num - 1 ) ; } else return ; } function subset ( nthBit , num , numOfBits ) { if ( nthBit >= 0 ) { if ( num & ( 1 << nthBit ) ) { document . write ( numOfBits - nthBit + " " ) ; } subset ( nthBit - 1 , num , numOfBits ) ; } else return ; } var n = 4 ; printSubsets ( n , Math . pow ( 2 , n ) - 1 ) ;