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
def printSubsets ( numOfBits , num ) : NEW_LINE INDENT if num >= 0 : NEW_LINE INDENT print ( " { " , end = " ▁ " ) NEW_LINE subset ( numOfBits - 1 , num , numOfBits ) NEW_LINE print ( " } " ) NEW_LINE printSubsets ( numOfBits , num - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return NEW_LINE DEDENT DEDENT def subset ( nthBit , num , numOfBits ) : NEW_LINE INDENT if nthBit >= 0 : NEW_LINE INDENT if num & ( 1 << nthBit ) != 0 : NEW_LINE INDENT print ( numOfBits - nthBit , end = " ▁ " ) NEW_LINE DEDENT subset ( nthBit - 1 , num , numOfBits ) NEW_LINE DEDENT else : NEW_LINE INDENT return NEW_LINE DEDENT DEDENT n = 4 NEW_LINE printSubsets ( n , 2 ** n - 1 ) NEW_LINE