Javatpoint Logo
Javatpoint Logo

All Possible Combinations of a String in Java

One of the most popular programming problems is to create every conceivable string combination. There are a few ways to do this with Java, including repetition, and recursion. We will examine many approaches to producing every possible combination of a given string in this section.

Method 1: Using Recursion

AllCombinations.java

Output:

abc
ab
ac
a
bc
b
c

Explanation

Recursion is used in this approach to produce every conceivable combination. Starting with the entire string, we build combinations at each step by adding or removing the initial character. We publish the current combination when the string remains empty. Until every possible combination is created, the recursion keeps going.

Method 2: Using Iteration

AllCombinations.java

Output:

abc
ab
ac
a
bc
b
c

Method 3: Using Arrays

Combinations.java

Output:

abc acb bac bca cab cba

Explanation

We construct a printDistinctPermutations function, which accepts as parameters the current permutation and the input string. We output the current permutation and return if the string is empty. The characters that have been utilized are tracked using a 26-character boolean array.

We go over the input string iteratively, making sure that every character has been used. If not, we update the used array to indicate that the character has been used and do a recursive call with the character deleted from the remaining string.

The input string "abc" is passed to printDistinctPermutations in the main procedure.

Method 4: Character Swapping

Combinations.java

Output:

abc acb bac bca cba cab

Explanation

The left index represents the character that starts, while the right index represents the character that finishes. If there is a permutation that results from the left index equalling the right index, we show the text.

If not, we swap the characters at the left index and the current index as we cycle over the characters in the string. The modified text and the left index, which has been increased by one, are then sent to a recursive function.

We retrace our steps by placing the characters in their initial locations after the recursive call to investigate other possibilities.

Characters in the string can be switched around using the swap technique.

Conclusion

These techniques provide several strategies for resolving the Java challenge of producing every conceivable string combination, accommodating various programming philosophies and tastes. We may select the approach that best meets your demands based on your unique requirements and available space.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA