Print all the combinations of a string in lexicographical order
Given a string str, print of all the combinations of a string in lexicographical order.
Input: str = "ABC" Output: A AB ABC AC ACB B BA BAC BC BCA C CA CAB CB CBA Input: ED Output: D DE E ED
Approach: Count the occurrences of all the characters in the string using a map, then using recursion all the possible combinations can be printed. Store the elements and their counts in two different arrays. Three arrays are used, input array which has the characters, count array has the count of characters and result is a temporary array which is used in recursion to generate all the combinations. Using recursion and backtracking all the combinations can be printed.
Below is the implementation of the above approach.
A AB ABC AC ACB B BA BAC BC BCA C CA CAB CB CBA
Time Complexity: O() where N is the size of the string.
Auxiliary Space: O(N)