All combinations of a String In Java

To find the combinations of a string, either the logic needs to use for loop or recursive loop.

As for loop depends on the string length, for each loop we have to write the logic again, as more swapping will happen when try to get the combinations.

Since swapping will happen recursively based on the positions of the input string, recursive function will be the best choice for finding all combinations of a String.

For Input: ABC

Output:

ABC
ACB
BAC
BCA
CAB
CBA

The above output is 2 Power n, where n is the length of the string.

The recursive logic is swapping each of the character to a different position., and continuing swapping until get all combinations.

For Input: ABC

Steps:

  1. Take A as index characters, and do the Swap between B & C.
    • ABC, BAC, CAB
  2. Since the first character is done, call the same method again and pass the remaining string(others) resulted from for loop.,
  3. Once the values are fetched, keep first character untouched and call the same method again.

Output:

ABC
ACB
BAC
BCA
CAB
CBA

Leave a Reply

Your email address will not be published. Required fields are marked *