fork(11) download
  1. #include<vector>
  2. #include<algorithm>
  3. #include<iostream>
  4. #include<string>
  5. using namespace std;
  6. string insertCharAt(string word,char c,int i)
  7. {
  8. string start = word.substr(0, i);
  9. string end = word.substr(i);
  10. return start + c + end;
  11. }
  12. vector<string> getPermutation(string str)
  13. {
  14. //if(str.empty())
  15. //return (vector<string>());
  16. vector<string> permutations;
  17. if(str.length()==0)
  18. {
  19. permutations.push_back("");
  20. return permutations;
  21. }
  22. char first=str.at(0);
  23. string remainder=str.substr(1);
  24. vector<string> words=getPermutation(remainder);
  25. for(unsigned int i=0;i<words.size();i++)
  26. {
  27. string temp=words[i];
  28. for(unsigned int j=0;j<=temp.length();j++)
  29. {
  30. string s=insertCharAt(temp,first,j);
  31. permutations.push_back(s);
  32. }
  33.  
  34. }
  35. return permutations;
  36. }
  37.  
  38. int main()
  39. {
  40. string str="ABCD";
  41. vector<string> permutation=getPermutation(str);
  42. for(unsigned int i=0;i<permutation.size();i++)
  43. cout<<permutation[i]<<"\n";
  44. return 0;
  45. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
ABCD
BACD
BCAD
BCDA
ACBD
CABD
CBAD
CBDA
ACDB
CADB
CDAB
CDBA
ABDC
BADC
BDAC
BDCA
ADBC
DABC
DBAC
DBCA
ADCB
DACB
DCAB
DCBA