Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all possible permutation of a string

I have the following program for finding all possible permutations of a 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));
          permute(a, i+1, n);
          swap((a+i), (a+j)); //backtrack
       }
   }
}

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

I need to know is there any better way(efficient) to find all permutations because this algorithm is having O(n^n) efficiency.

Thank you.. :-)

like image 532
Gokul Avatar asked Mar 17 '23 11:03

Gokul


1 Answers

It is there in standard

#include<algorithm>
std::vector<int> vec;
std::next_permutation(std::begin(vec), std::end(vec));

In case of string

# include<string>
#include<algorithm>

std::string str ="abcd"
do{
     std::cout<<str<<"\n";

} while(std::next_permutation(std::begin(str), std::end(str)));
like image 193
Steephen Avatar answered Mar 19 '23 03:03

Steephen