Last active
June 7, 2018 21:03
-
-
Save patelpreet422/c1994dfdd0a9af525b43bda9629960dc to your computer and use it in GitHub Desktop.
Permutation in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <algorithm> | |
void permuteHelper(std::string s, std::string chosen) | |
{ | |
if (s.empty()) | |
{ | |
std::cout << chosen << '\n'; | |
return; | |
} | |
for (int i = 0; i < s.length(); ++i) | |
{ | |
char c = s[i]; | |
//add c to the string of characters already chosen | |
chosen += c; | |
/* | |
remove c from s so that we can call permuteHelper | |
for the rest of the string which do not contain c | |
*/ | |
s.erase(i, 1); | |
permuteHelper(s, chosen); | |
/* | |
since our permuteHelper call is completed remove the same | |
character from the end of chosen that we appended before | |
*/ | |
chosen.erase(chosen.length() - 1, 1); | |
/* | |
put that same character c that we removed earlier in its original | |
place, so that our string is ready for the next iteration | |
*/ | |
s.insert(i, 1, c); | |
} | |
} | |
void permute(std::string s) | |
{ | |
permuteHelper(s, ""); | |
} | |
int main() | |
{ | |
std::string s{ "ABC" }; | |
permute(s); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment