Given a string str, the task is to print all the distinct permutations of str.
A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement.
For instance, the words ‘bat’ and ‘tab’ represents two distinct permutation (or arrangements) of a similar three letter word.
Examples:
Input: str = “abbb”
Output: [abbb, babb, bbab, bbba]
Input: str = “abc”
Output: [abc, bac, bca, acb, cab, cba]
Approach: Write a recursive function that will generate all the permutations of the string. Terminating condition will be when the passed string is empty, in that case the function will return an empty ArrayList. Before adding the generated string, just check if it has already been generated before to get the distinct permutations.
Below is the implementation of the above approach:
Java
import java.util.ArrayList;
public class GFG {
static boolean isPresent(String s, ArrayList<String> Res)
{
for (String str : Res) {
if (str.equals(s))
return true ;
}
return false ;
}
static ArrayList<String> distinctPermute(String str)
{
if (str.length() == 0 ) {
ArrayList<String> baseRes = new ArrayList<>();
baseRes.add( "" );
return baseRes;
}
char ch = str.charAt( 0 );
String restStr = str.substring( 1 );
ArrayList<String> prevRes = distinctPermute(restStr);
ArrayList<String> Res = new ArrayList<>();
for (String s : prevRes) {
for ( int i = 0 ; i <= s.length(); i++) {
String f = s.substring( 0 , i) + ch + s.substring(i);
if (!isPresent(f, Res))
Res.add(f);
}
}
return Res;
}
public static void main(String[] args)
{
String s = "abbb" ;
System.out.println(distinctPermute(s));
}
}
|
Output[abbb, babb, bbab, bbba]
Time Complexity: O(n*n!)
Auxiliary space: O(n)
Optimization : We can optimize above solution to use HashSet to store result strings in place of Res ArrayList.