Permutations of a given string

PROBLEM :

Given a string, print all permutations of a given string.

Input:
The first line of input contains an integer T denoting the number of test cases.
Each test case contains a single string in capital letter.

Output:
Print all permutations of a given string with single space and all permutations should be in lexicographically increasing order.

Constraints:
1 = T = 10
1 = size of string = 5

Example:
Input:
2
ABC
ABSG

Output:
ABC ACB BAC BCA CAB CBA
ABGS ABSG AGBS AGSB ASBG ASGB BAGS BASG BGAS BGSA BSAG BSGA GABS GASB GBAS GBSA GSAB GSBA SABG SAGB SBAG SBGA SGAB SGBA

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
#include<vector>
#include<algorithm>
#include<string.h>
using namespace std;

vector<string>v;
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

void permutation(char s[],int l,int h)
{
    int i;
    if(l==h)
    {
        if(find(v.begin(),v.end(),s)==v.end())
            v.push_back(s);
    }
    else
    {
        for(i=l;i<=h;i++)
        {
            swap((s+l),(s+i));
            permutation(s,l+1,h);
            swap((s+l),(s+i));
        }
    }
}

int main()
 {
    int t,l;
    char s[10];
cin>>t;
while(t--)
{
   v.clear();
 
   cin>>s;
   l=strlen(s);
 
   permutation(s,0,l-1);
 
   sort(v.begin(),v.end());
 
   vector<string>::iterator i;
   for(i=v.begin();i!=v.end();i++)
       cout<<*i<<" ";
     
   cout<<"\n";
}
return 0;
}

--------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )