Hoán vị

Hoán vị là trường hợp đặc biệt của chỉnh hợp không lặp với k = n

#include <stdio.h>
#include <string.h>

/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. left: Starting index of the string
   3. right: Ending index of the string. */
void permute(char *a, int left, int right)
{
    int i;
    if (left == right)
        printf("%s\n", a);
    else
    {
        for (i = left; i <= right; i++)
        {
            swap((a+left), (a+i));
            permute(a, left+1, right);
            swap((a+left), (a+i)); //backtrack
        }
    }
}

/* Driver program to test above functions */
int main()
{
    char str[] = "ABC";
    int n = strlen(str);
    permute(str, 0, n-1);
    return 0;
}

results matching ""

    No results matching ""