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++
#include <bits/stdc++.h>
using namespace std;
void printResult( char * result, int len)
{
for ( int i = 0; i <= len; i++)
cout << result[i];
cout << endl;
}
void stringCombination( char result[], char str[], int count[],
int level, int size, int length)
{
if (level == size)
return ;
for ( int i = 0; i < length; i++) {
if (count[i] == 0)
continue ;
count[i]--;
result[level] = str[i];
printResult(result, level);
stringCombination(result, str, count,
level + 1, size, length);
count[i]++;
}
}
void combination(string str)
{
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;
}
char * input = new char [mp.size()];
int * count = new int [mp.size()];
char * result = new char [str.size()];
map< char , int >::iterator it = mp.begin();
int i = 0;
for (it; it != mp.end(); it++) {
input[i] = it->first;
count[i] = it->second;
i++;
}
int length = mp.size();
int size = str.size();
stringCombination(result, input, count,
0, size, length);
}
int main()
{
string str = "ABC" ;
combination(str);
return 0;
}
|
Java
import java.util.HashMap;
class GFG
{
static void printResult( char [] result,
int len)
{
for ( int i = 0 ; i <= len; i++)
System.out.print(result[i]);
System.out.println();
}
static void stringCombination( char [] result, char [] str,
int [] count, int level,
int size, int length)
{
if (level == size)
return ;
for ( int i = 0 ; i < length; i++)
{
if (count[i] == 0 )
continue ;
count[i]--;
result[level] = str[i];
printResult(result, level);
stringCombination(result, str, count,
level + 1 , size, length);
count[i]++;
}
}
static void combination(String str)
{
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 );
char [] input = new char [mp.size()];
int [] count = new int [mp.size()];
char [] result = new char [str.length()];
int i = 0 ;
for (HashMap.Entry<Character,
Integer> entry : mp.entrySet())
{
input[i] = entry.getKey();
count[i] = entry.getValue();
i++;
}
int length = mp.size();
int size = str.length();
stringCombination(result, input, count, 0 ,
size, length);
}
public static void main (String[] args)
{
String str = "ABC" ;
combination(str);
}
}
|
Python3
from collections import defaultdict
def printResult(result, length):
for i in range (length + 1 ):
print (result[i], end = "")
print ()
def stringCombination(result, st, count,
level, size, length):
if (level = = size):
return
for i in range (length):
if (count[i] = = 0 ):
continue
count[i] - = 1
result[level] = st[i]
printResult(result, level)
stringCombination(result, st, count,
level + 1 , size, length)
count[i] + = 1
def combination(st):
mp = defaultdict( int )
for i in range ( len (st)):
if (st[i] in mp.keys()):
mp[st[i]] = mp[st[i]] + 1
else :
mp[st[i]] = 1
input = [''] * len (mp)
count = [ 0 ] * len (mp)
result = [''] * len (st)
i = 0
for key, value in mp.items():
input [i] = key
count[i] = value
i + = 1
length = len (mp)
size = len (st)
stringCombination(result, input , count,
0 , size, length)
if __name__ = = "__main__" :
st = "ABC"
combination(st)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void printResult( char [] result,
int len)
{
for ( int i = 0; i <= len; i++)
Console.Write(result[i]);
Console.WriteLine();
}
static void stringCombination( char [] result, char [] str,
int [] count, int level,
int size, int length)
{
if (level == size)
return ;
for ( int i = 0; i < length; i++)
{
if (count[i] == 0)
continue ;
count[i]--;
result[level] = str[i];
printResult(result, level);
stringCombination(result, str, count,
level + 1, size, length);
count[i]++;
}
}
static void combination(String str)
{
int i;
Dictionary< char , int > mp = new Dictionary< char , int >();
for (i= 0; i < str.Length; i++)
if (mp.ContainsKey(str[i]))
mp[str[i]] = mp[str[i]] + 1;
else
mp.Add(str[i], 1);
char [] input = new char [mp.Count];
int [] count = new int [mp.Count];
char [] result = new char [str.Length];
i = 0;
foreach (KeyValuePair< char , int > entry in mp)
{
input[i] = entry.Key;
count[i] = entry.Value;
i++;
}
int length = mp.Count;
int size = str.Length;
stringCombination(result, input, count, 0,
size, length);
}
public static void Main(String[] args)
{
String str = "ABC" ;
combination(str);
}
}
|
Javascript
<script>
function printResult(result, len) {
for ( var i = 0; i <= len; i++) document.write(result[i]);
document.write( "<br>" );
}
function stringCombination(result, str, count, level, size, len) {
if (level === size) return ;
for ( var i = 0; i < len; i++) {
if (count[i] === 0) continue ;
count[i]--;
result[level] = str[i];
printResult(result, level);
stringCombination(result, str, count, level + 1, size, len);
count[i]++;
}
}
function combination(str) {
var i;
var mp = {};
for (i = 0; i < str.length; i++)
if (mp.hasOwnProperty(str[i])) mp[str[i]] = mp[str[i]] + 1;
else mp[str[i]] = 1;
var input = new Array(Object.keys(mp).length).fill(0);
var count = new Array(Object.keys(mp).length).fill(0);
var result = new Array(str.length).fill(0);
i = 0;
for (const [key, value] of Object.entries(mp)) {
input[i] = key;
count[i] = value;
i++;
}
var len = Object.keys(mp).length;
var size = str.length;
stringCombination(result, input, count, 0, size, len);
}
var str = "ABC" ;
combination(str);
</script>
|
Output: 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)
|