Permutations without Dups
input = abc
iterations:
0: _ # base case
1: a # insert a at every position of parent string
2: ba, ab # insert b at every position of parent string
3: cba, acb, bac, cab, acb, abc # insert c at every position of parent stringvector<string> addCharToEach(vector<string> ¤t_perms, string addChar) {
vector<string> newPerms;
string temp;
for (int i = 0; i < current_perms.size(); i++) {
// addChar to every position in the previous vector
for (int j = 0; j <= current_perms.at(i).size(); j++) {
temp = current_perms.at(i);
temp.insert(j, addChar);
newPerms.push_back(temp);
}
}
return newPerms;
}
vector<string> permutations(string str) {
vector <string> permutations;
if (str.length() == 0) return permutations;
// start us off
string temp(1, str[0]);
permutations.push_back(temp);
for (int i = 1; i < str.length(); i++) {
string temp(1, str[i]);
permutations = addCharToEach(permutations, temp);
}
return permutations;
}Last updated