What is the solution for getting all the permutations of a given string using a recursive method
May 10, 2018 in Java 1,997 views

## 2 answers to this question.

This is the recursive way of finding a solution for this program:

```public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String pre, String str) {
int num = str.length();
if (num == 0) System.out.println(pre);
else {
for (int i = 0; i < num; i++)
permutation(pre + str.charAt(i), str.substring(0, i) + str.substring(i+1, num));
}
}```
answered May 10, 2018 by
• 3,370 points

You could use recursion to do this.

•  Try each of the letters in turn as the first letter and then find all the permutations of the remaining letters using a recursive call.

•  The base case is when the input is an empty string the only permutation is the empty string

Here's how you could probably implement it:

```public class PermutationsTest {
public static void main(String[] args) throws Exception {
String str = "sample";
StringBuffer strBuf = new StringBuffer(str);
doPerm(strBuf,0);
}
private static void doPerm(StringBuffer str, int index){
if(index == str.length())
System.out.println(str);
else { //recursively solve this by placing all other chars at current first pos
doPerm(str, index+1);
for (int i = index+1; i < str.length(); i++) {//start swapping all other chars with current first char
swap(str,index, i);
doPerm(str, index+1);
swap(str,i, index);//restore back my string buffer
}
}
}
private  static void swap(StringBuffer str, int pos1, int pos2){
char c1 = str.charAt(pos1);
str.setCharAt(pos1, str.charAt(pos2));
str.setCharAt(pos2, c1);
}}   ```
answered Aug 21, 2019 by
• 59,230 points

## Listing all the subclasses of a specific class in Java

Try with BurningWave core library. Here an ...READ MORE

## What is the easiest way to iterate through the characters of a string in Java?

There are two approaches to this: for(int i ...READ MORE

## Unscramble Letters in Java - Get all possible combinations of the letters

I am currently an AP Computer Science ...READ MORE

## How do I create a Java string from the contents of a file?

If you're looking for an alternative that ...READ MORE

## Result of character addition in Java

Binary arithmetic operations on char and byte ...READ MORE

## How to convert byte array to String and STring to byte array?

The best possible way of conversion between byte[] and String is to ...READ MORE

## Change date format in a Java string

The reason for the inaccuracy is because ...READ MORE

## Encode String to UTF-8

String objects in Java use the UTF-16 ...READ MORE