Write a Java program to generate all permutations of a string.

For example, the string ABC has 6 permutations, i.e., ABC, ACB, BAC, BCA, CBA, CAB.

Practice this problem

1. Recursive Approach

Since the string is immutable in Java, the idea is to convert the string into a character array. Then we can in-place generate all permutations of the given string using backtracking by swapping each of the remaining characters in the string with its first character and then generating all the permutations of the remaining characters using a recursive call.

Below is the recursion tree for printing all permutations of the string “ABC”, followed by the Java implementation.

Generate all permutations of a string

Download  Run Code

Output:

ABC
ACB
BAC
BCA
CBA
CAB

 
Here’s another Java implementation that doesn’t convert the string into a character array.

Download  Run Code

Output:

ABC
ACB
BAC
BCA
CAB
CBA

2. Iterative Approach: Using Collection

The following implementation uses ArrayList to store the partially generated permutations and then use it to generate the final permutations in further iterations.

Download  Run Code

Output:

[CAB, ACB, ABC, CBA, BCA, BAC]

 
Author: Lucas Daniel

 
Also see:

Find all lexicographic permutations of a string