Generate all possible combinations of at most X characters from a given array

• Last Updated : 22 Apr, 2021

Given an array arr[] consisting of N characters, the task is to generate all possible combinations of at most X elements ( 1 ≤ X ≤ N).

Examples:

Input: N = 3, X = 2, arr[] = {‘a’, ‘b’, ‘a’}
Output: a b c bc ca ab cb ac ba
Explanation: All possible combinations using 1 character is 3 {‘a’, ‘b’, ‘c’}. All possible combinations using 2 characters are {“bc” “ca” “ab” “cb” “ac” “ba”}.

Input: N = 3, X = 3, arr[] = {‘d’, ‘a’, ‘b’}

Approach: The given problem can be solved using the Dynamic Programming approach. Follow the below steps to solve the problem:

1. Generate all possible permutations that can be created with 1 character, which is the given array arr[].
2. Store all permutations.
3. Once stored, generate all possible permutations of 2 characters and store them.
4. Once the last step is completed, discard all permutations of a single character.
5. Iteratively, in the same way, calculate the permutations until X is reached.

Below is the implementation of the above approach:

C++

 // C++ program for the above approach#include using namespace std; // Function to generate permutations of// at most X elements from array arr[]void differentFlagPermutations(int X,                               vector arr){    vector ml;    ml = arr;         for(int i = 0; i < ml.size(); i++)    {        cout << ml[i] << " ";    }     int count = ml.size();       // Traverse all possible lengths    for(int z = 0; z < X - 1; z++)    {                 // Stores all combinations        // of length z        vector tmp;                   // Traverse the array        for(int i = 0; i < arr.size(); i++)        {            for(int k = 0; k < ml.size(); k++)            {                if (arr[i] != ml[k])                {                                         // Generate all                    // combinations of length z                    tmp.push_back(ml[k] + arr[i]);                    count += 1;                }            }        }                     // Print all combinations of length z        for(int i = 0; i < tmp.size(); i++)        {            cout << tmp[i] << " ";        }                   // Replace all combinations of length z - 1        // with all combinations of length z        ml = tmp;    }} // Driver Codeint main(){         // Given array    vector arr{ "c", "a", "b" };         // Given X    int X = 2;           differentFlagPermutations(X, arr);         return 0;} // This code is contributed by divyeshrabadiya07

Java

 // Java program for the above approachimport java.util.*;class GFG{ // Function to generate permutations of// at most X elements from array arr[]static void differentFlagPermutations(int X,                               String[] arr){    String[] ml = arr;         for(int i = 0; i < ml.length; i++)    {        System.out.print(ml[i] + " ");    }     int count = ml.length;       // Traverse all possible lengths    for(int z = 0; z < X - 1; z++)    {                 // Stores all combinations        // of length z        Vector tmp = new Vector();                   // Traverse the array        for(int i = 0; i < arr.length; i++)        {            for(int k = 0; k < ml.length; k++)            {                if (arr[i] != ml[k])                {                                         // Generate all                    // combinations of length z                    tmp.add(ml[k] + arr[i]);                    count += 1;                }            }        }                     // Print all combinations of length z        for(int i = 0; i < tmp.size(); i++)        {            System.out.print(tmp.get(i) + " ");        }                   // Replace all combinations of length z - 1        // with all combinations of length z        ml = tmp.toArray(new String[tmp.size()]);;    }} // Driver Codepublic static void main(String[] args){         // Given array    String []arr = { "c", "a", "b" };         // Given X    int X = 2;         differentFlagPermutations(X, arr);  }} // This code is contributed by shikhasingrajput

Python3

 # Python3 program for the above approach # Function to generate permutations of# at most X elements from array arr[]def differentFlagPermutations(X, arr):     ml = arr.copy()     print(" ".join(ml), end =" ")    count = len(ml)     # Traverse all possible lengths    for z in range(X-1):                 # Stores all combinations        # of length z        tmp = []                 # Traverse the array        for i in arr:            for k in ml:                if i not in k:                                         # Generate all                    # combinations of length z                    tmp.append(k + i)                    count += 1                             # Print all combinations of length z        print(" ".join(tmp), end =" ")                 # Replace all combinations of length z - 1        # with all combinations of length z        ml = tmp  # Given arrayarr = ['c', 'a', 'b'] # Given XX = 2 differentFlagPermutations(X, arr)

C#

 // C# program for the above approachusing System;using System.Collections.Generic;class GFG{   // Function to generate permutations of  // at most X elements from array arr[]  static void differentFlagPermutations(int X, List arr)  {    List ml = new List();    ml = arr;    for(int i = 0; i < ml.Count; i++)    {      Console.Write(ml[i] + " ");    }     int count = ml.Count;     // Traverse all possible lengths    for(int z = 0; z < X - 1; z++)    {       // Stores all combinations      // of length z      List tmp = new List();       // Traverse the array      for(int i = 0; i < arr.Count; i++)      {        for(int k = 0; k < ml.Count; k++)        {          if (arr[i] != ml[k])          {             // Generate all            // combinations of length z            tmp.Add(ml[k] + arr[i]);            count += 1;          }        }      }           // Print all combinations of length z      for(int i = 0; i < tmp.Count; i++)      {        Console.Write(tmp[i] + " ");      }       // Replace all combinations of length z - 1      // with all combinations of length z      ml = tmp;    }  }   // Driver code  static void Main()  {         // Given array    List arr = new List(new string[] { "c", "a", "b" });     // Given X    int X = 2;     differentFlagPermutations(X, arr);  }} // This code is contributed by divyesh072019

Javascript


Output:
c a b ac bc ca ba cb ab

Time Complexity: O(X*N2)
Auxiliary Space: O(N2)

My Personal Notes arrow_drop_up