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.

Examples:

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.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find all combinations
// of a string in lexicographical order
#include <bits/stdc++.h>
using namespace std;
  
// function to print string
void printResult(char* result, int len)
{
    for (int i = 0; i <= len; i++)
        cout << result[i];
    cout << endl;
}
  
// Method to found all combination
// of string it is based in tree
void stringCombination(char result[], char str[], int count[],
                       int level, int size, int length)
{
    // return if level is equal size of string
    if (level == size)
        return;
  
    for (int i = 0; i < length; i++) {
  
        // if occurrence of char is 0 then
        // skip the iteration of loop
        if (count[i] == 0)
            continue;
  
        // decrease the char occurrence by 1
        count[i]--;
  
        // store the char in result
        result[level] = str[i];
  
        // print the string till level
        printResult(result, level);
  
        // call the function from level +1
        stringCombination(result, str, count,
                          level + 1, size, length);
  
        // backtracking
        count[i]++;
    }
}
  
void combination(string str)
{
  
    // declare the map for store
    // each char with occurrence
    map<char, int> mp;
  
    for (int i = 0; i < str.size(); i++) {
  
        if (mp.find(str[i]) != mp.end())
            mp[str[i]] = mp[str[i]] + 1;
        else
            mp[str[i]] = 1;
    }
  
    // initialize the input array
    // with all unique char
    char* input = new char[mp.size()];
  
    // initialize the count array with
    // occurrence the unique char
    int* count = new int[mp.size()];
  
    // temporary char array for store the result
    char* result = new char[str.size()];
  
    map<char, int>::iterator it = mp.begin();
    int i = 0;
  
    for (it; it != mp.end(); it++) {
        // store the element of input array
        input[i] = it->first;
  
        // store the element of count array
        count[i] = it->second;
        i++;
    }
  
    // size of map(no of unique char)
    int length = mp.size();
  
    // size of original string
    int size = str.size();
  
    // call function for print string combination
    stringCombination(result, input, count,
                      0, size, length);
}
  
// Driver code
int main()
{
    string str = "ABC";
    cin >> str;
  
    combination(str);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find all combinations 
// of a string in lexicographical order
import java.util.HashMap;
  
class GFG 
{
      
    // function to print string
    static void printResult(char[] result,
                            int len)
    {
        for (int i = 0; i <= len; i++)
            System.out.print(result[i]);
        System.out.println();
    }
      
    // Method to found all combination 
    // of string it is based in tree
    static void stringCombination(char[] result, char[] str, 
                                  int[] count, int level, 
                                  int size, int length)
    {
          
        // return if level is equal size of string
        if (level == size) 
            return;
          
        for (int i = 0; i < length; i++)
        {
              
            // if occurrence of char is 0 then 
            // skip the iteration of loop
            if (count[i] == 0
                continue;
              
            // decrease the char occurrence by 1
            count[i]--;
              
            // store the char in result
            result[level] = str[i];
              
            // print the string till level
            printResult(result, level);
              
            // call the function from level +1
            stringCombination(result, str, count, 
                              level + 1, size, length);
              
            // backtracking
            count[i]++;
        }
    }
      
    static void combination(String str)
    {
          
        // declare the map for store 
        // each char with occurrence
        HashMap<Character,
                Integer> mp = new HashMap<>();
          
        for (int i = 0; i < str.length(); i++)
            mp.put(str.charAt(i), mp.get(str.charAt(i)) == null ? 1
                                  mp.get(str.charAt(i)) + 1);
          
        // initialize the input array 
        // with all unique char
        char[] input = new char[mp.size()];
          
        // initialize the count array with 
        // occurrence the unique char
        int[] count = new int[mp.size()];
          
        // temporary char array for store the result
        char[] result = new char[str.length()];
          
        int i = 0;
        for (HashMap.Entry<Character,
                           Integer> entry : mp.entrySet())
        {
              
            // store the element of input array
            input[i] = entry.getKey();
              
            // store the element of count array
            count[i] = entry.getValue();
            i++;
        }
          
        // size of map(no of unique char)
        int length = mp.size();
          
        // size of original string
        int size = str.length();
          
        // call function for print string combination
        stringCombination(result, input, count, 0
                                    size, length);
    }
      
    // Driver code
    public static void main (String[] args)
    {
        String str = "ABC";
        combination(str);
    }
}
  
// This code is contributed by
// sanjeev2552

chevron_right


Output:

A
AB
ABC
AC
ACB
B
BA
BAC
BC
BCA
C
CA
CAB
CB
CBA


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : sanjeev2552