Write a program to print all permutations of a given string

Reference:

  1. GeeksforGeeks: Write a program to print all permutations of a given string
  2. 演算法筆記: Backtracking

void swap(char *a, char *b)
{
    if(*a == *b) return;
    *a = *a ^ *b;
    *b = *a ^ *b;
    *a = *a ^ *b;
}

void permute(char *a, int l, int r)
{
    int i;
    if (l == r)
        printf("%s\n", a);
    else
    {
        for (i = l; i <= r; i++)
        {
            swap((a+l), (a+i));     //change postion of letter
            permute(a, l+1, r);     //enter next level
            swap((a+l), (a+i));     //backtrack
        }
    }
}

String: "ABC"

Output:

ABC
ACB
BAC
BCA
CBA
CAB

Derivative Problem: List all combinations

void permute(char *a, int l, int r)
{
    int i, j;

    if (l == r)
        printf("%s\n", a);              //print combination of last level
    else
    {
        for (i = l; i <= r; i++)
        {
            swap((a+l), (a+i));         
            for (j = 0; j <= l; j++)    //print combination of every level without last level
                printf("%c", a[j]);
            printf("\n");
            permute(a, l+1, r);         
            swap((a+l), (a+i));         
        }
    }
}

String: "ABC"

Output:

A
AB
ABC
AC
ACB
B
BA
BAC
BC
BCA
C
CB
CBA
CA
CAB

results matching ""

    No results matching ""