Advertisement
montimaj

UNIQUE PERMUTATIONS

Apr 5th, 2014
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. #include<iostream>
  2. #include<string>
  3. #include<map>
  4. #include<algorithm>
  5. void gen_perm(std::map<std::string,int> &m,std::string s,int i,int n)
  6. {  
  7.   if(i==n-1)
  8.     m[s]++;
  9.   else
  10.   {
  11.     for(int j=i;j<n;++j)
  12.     {
  13.     std::swap(s[i],s[j]);
  14.     gen_perm(m,s,i+1,n);
  15.     std::swap(s[i],s[j]);
  16.     }
  17.   }
  18. }
  19. void gen_perm_stl(std::string s)
  20. {
  21.   std::sort(s.begin(),s.end());
  22.   do  
  23.     std::cout<<s<<"\n";  
  24.   while(std::next_permutation(s.begin(),s.end()));
  25. }
  26. int main()
  27. {
  28.   std::string s;
  29.   std::map<std::string,int> m;
  30.   std::cout<<"Enter a string: ";
  31.   std::cin>>s;  
  32.   std::cout<<"\nPermutations: \n";
  33.   //gen_perm_stl(s); // call any one function.. stl obviously performs better
  34.   gen_perm(m,s,0,s.length());
  35.   for(auto it=m.begin();it!=m.end();++it)
  36.     std::cout<<it->first<<"\n";
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement