In below code we will be using simple recursion to create all possible permutations.
- we will be creating an inp array, for convienience as we wil be removing elements from this array each time we append to the result, so that the next permtn will exclude already used elements.
- Stringbuilder is used to append each char.
Algo;
if input array is empty, i.e no more elements need to be added, store the string in result.
else travel through the input array, append the char to stringBuilder, remove it from input arrayList
and call append method again.
After returning, revert back the changes.
Kl refer below code
import java.util.* ;
import java.io.*;
public class Solution {
public static List<String> findPermutations(String s) {
List<String> res = new ArrayList<>();
List<Character> inp = new ArrayList<>(s.length());
for(int i=0; i<s.length(); i++)
inp.add(s.charAt(i));
StringBuilder b = new StringBuilder();
append(b, inp, res);
return res;
}
public static void append(StringBuilder b, List<Character> inp, List<String> res){
if(inp.size() == 0){
res.add(b.toString());
return;
}
for(int i=0; i<inp.size(); i++){
char c = inp.get(i);
b.append(c);
inp.remove(i);
append(b, inp, res);
inp.add(i, c);
b.deleteCharAt(b.length()-1);
}
}
}
Happy coding ; ~)


