Permutation of String in c++

Hello people again , one day I was thinking calculating all permutations of string in c++ is difficult
but now when I got familiar with recursion that was so easy to do the job.
I had seen many codes on internet but didn’t get anyone. Here is my code. It’s self explanatory.

#include <cstdio>

#include <iostream>

#include <string>

#include <vector>

using namespace std;

vector<string> permute(string ,int );

main()

{

string s=”1234″;

vector<string> output=permute(s,s.size());

for(int i=0;i<output.size();i++)

cout<<output[i]<<endl;

}

vector<string> permute(string s,int n) //this will return all permutions of string s as array of strings

{

if(n==1)

{

vector<string> v;

v.push_back(s);

return v;

}

else

{

vector<string> v;

for(int i=0;i<s.size();i++)

{

string temp=”";

for(int j=0;j<s.size();j++)

if(j!=i) temp+=s[j]; // temp is string of all charactor in s except s[i]

vector<string> vv;

vv = permute(temp,n-1); // logic is keep s[i] to first place and concatinate it with all permution of temp

for(int k=0;k<vv.size();k++)

v.push_back(s[i]+vv[k]);

}

return v;

}

}

Advertisement

~ by prashantthorat on March 1, 2010.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.