Produce every ordering of the characters of a string (e.g. "abc" -> abc, acb, bac, bca, cab, cba).
Use backtracking/recursion: fix each character at the current position and recurse on the rest, swapping back after each choice. There are n! permutations, so the time is O(n * n!). Deduplicate if the input has repeated characters.
public static List<String> permutations(String s) {
List<String> out = new ArrayList<>();
permute(s.toCharArray(), 0, out);
return out;
}
private static void permute(char[] a, int k, List<String> out) {
if (k == a.length) { out.add(new String(a)); return; }
for (int i = k; i < a.length; i++) {
char t = a[k]; a[k] = a[i]; a[i] = t; // swap
permute(a, k + 1, out);
t = a[k]; a[k] = a[i]; a[i] = t; // undo
}
}function permutations(s) {
const out = [];
const a = s.split('');
(function permute(k) {
if (k === a.length) { out.push(a.join('')); return; }
for (let i = k; i < a.length; i++) {
[a[k], a[i]] = [a[i], a[k]];
permute(k + 1);
[a[k], a[i]] = [a[i], a[k]];
}
})(0);
return out;
}from itertools import permutations as perm
def permutations(s):
return [''.join(p) for p in perm(s)]Permutation generation shows up in exhaustive test-input generation and combinatorial search; interviewers use it to test recursion and backtracking discipline.
For "aab" your code prints 6 permutations but several are identical. How do you return only distinct ones?