Print all permutations of a string.
#include <stdio.h>
#include <string.h>
static void swap(char *a, char *b) { char t = *a; *a = *b; *b = t; }
void permute(char *s, int l, int r)
{
if (l == r) { puts(s); return; }
for (int i = l; i <= r; i++) {
int dup = 0; /* skip repeated letters at this position */
for (int k = l; k < i; k++) if (s[k] == s[i]) { dup = 1; break; }
if (dup) continue;
swap(&s[l], &s[i]);
permute(s, l + 1, r);
swap(&s[l], &s[i]); /* backtrack */
}
}
/* char str[] = "abc"; permute(str, 0, 2); -> abc acb bac bca cba cab */
Points: fix one position at a time by swapping each remaining character into it, recurse, then swap back (backtracking). There are n! permutations, so time is O(n · n!); recursion depth is n. The duplicate check avoids printing the same permutation twice for inputs like "aab". The string must be writable (an array, not a literal).