Thursday, September 13, 2012

Find all permutations of a given string


# include <stdio.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. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int i, int n)
{
   int j;
   if (i == n)
     printf("%s\n", a);
   else
   {
        for (j = i; j <= n; j++)
       {
          swap((a+i), (a+j));
            printf(" 1%s      ", a);
          permute(a, i+1, n);
          printf(" 2%s   %d   ", a, i);

          swap((a+i), (a+j)); //backtrack
       }
   }
}

/* Driver program to test above functions */
int main()
{
   char a[] = "AAC";
   permute(a, 0, 2);
   getchar();
   return 0;
}

2 comments:

  1. Great post! I found this page helpful as well:

    http://www.programmerinterview.com/index.php/recursion/permutations-of-a-string/

    ReplyDelete
  2. EPL Betting Tips reddit and how to make money by 카지노 가입 쿠폰 카지노 가입 쿠폰 カジノ シークレット カジノ シークレット 9220Chiefs Bills Bills Bills Bills Bills Bills Bills Bills

    ReplyDelete