![]() |
VOOZH | about |
Given a string of distinct characters, print all possible strings of any length that can be formed from given string characters. Examples:
Input: abc
Output: a b c abc ab ac bc bac bca
cb ca ba cab cba acb
Input: abcd
Output: a b ab ba c ac ca bc cb abc acb bac
bca cab cba d ad da bd db abd adb bad
bda dab dba cd dc acd adc cad cda dac
dca bcd bdc cbd cdb dbc dcb abcd abdc
acbd acdb adbc adcb bacd badc bcad bcda
bdac bdca cabd cadb cbad cbda cdab cdba
dabc dacb dbac dbca dcab dcba
Approach 1:
The generation of all strings include the following steps.
1) Generate all subsequences of given string.
2) For every subsequence 'subs', print all permutations of 'subs'
Below is C++ implementation. It uses next_permutation function in C++.
a b ab ba c ac ca bc cb abc acb bac bca cab cba
Time complexity: O(n * 2^n * n!)
Auxiliary Space : O(2^n * n)
Approach 2 :
- Generate all possible combinations of the given string using a bitmask.
- For each combination, generate all possible permutations of the characters in that combination.
- Print each permutation.
Below is the code for the above approach:
a b ab ba c ac ca bc cb abc acb bac bca cab cba
Time complexity : O(n * 2^n * n!)
Auxiliary Space : O(n)