all permutation using recursion

#include <iostream> #include <bits/stdc++.h> using namespace std; int len = 0; void get_count(string s,map<char,int> &count1){ for(auto c : s){ //char c = i; map<char,int> :: iterator it = count1.find(c); if(it==count1.end()){ count1.insert(make_pair(c,1)); } else{ it->second = (it->second)+1; } } } void perm(string so_far,map<char,int> count1,std::vector<string> &result){ map<char,int> count2(count1); if(so_far.length()==len){ result.push_back(so_far); // cout<<"pushed\n"; } map<char,int> :: iterator it = count2.begin(); while(it!=count2.end()){ int x = it->second ; if(x>0){ //cout<<"called\n"; map<char,int> count3(count1); char c = it->first; it->second = --x; string new_so_far = so_far+ c; map<char,int>::iterator it2 = count3.find(c); it2->second = (it2->second)-1; //cout<<new_so_far<<endl; perm(new_so_far,count3,result); } it++; } } int main () { int t; cin>>t; string s; while(t-->0){ std::vector<string> result; map<char,int> count1; cin>>s; len =s.length(); get_count(s,count1); perm("",count1,result); for(int i=0;i<result.size();i++){ cout<<result[i]<<" "; //result.erase(result.begin()+i+1); } cout<<endl; } return 0; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.