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
