![]() |
VOOZH | about |
Given a set represented as a string, write a recursive code to print all subsets of it. The subsets can be printed in any order.
Examples:
Input : set = "abc"
Output : { "", "a", "b", "c", "ab", "ac", "bc", "abc"}Input : set = "abcd"
Output : { "", "a" ,"ab" ,"abc" ,"abcd", "abd" ,"ac" ,"acd", "ad" ,"b", "bc" ,"bcd" ,"bd" ,"c" ,"cd" ,"d" }
The idea is to consider two cases for every character.
(i) Consider current character as part of current subset
(ii) Do not consider current character as part of the current subset.
Follow the approach to implement the above idea:
abc ab ac a bc b c
Time Complexity: O(2n)
Auxiliary Space: O(n), For recursive call stack
The idea is to fix a prefix, and generate all subsets beginning with the current prefix. After all subsets with a prefix are generated, replace the last character with one of the remaining characters.
Follow the approach to implement the above idea:
Follow the steps below to implement the above approach:
a ab abc ac b bc c
Time Complexity: O(2n)
Auxiliary Space: O(n), For recursive call stack
The idea is to pick each element one by one from the input set, then generate a subset for the same, and we follow this process recursively.
Follow the steps below to implement the above idea:
Follow the steps below to implement the above approach:
[[], [a], [b], [a, b], [c][/c], [a, c], [b, c], [a, b, c]]
Time Complexity: O(n*2n)
Auxiliary Space: O(n), For recursive call stack