Quantcast
Channel: Esdee
Viewing all articles
Browse latest Browse all 31

generate permutations of letters in a string

$
0
0
how to generate all permutations of the letters in a string? one method i like, for its intuitiveness - go to the last letter of the string and then recursively create strings by inserting previous letters in all possible positions. at each step a new list of strings will be created, with growing lengths


#include
#include
#include

std::vector<:string> permute(std::string s, size_t index) {
//std::cout std::vector<:string> perms;
if (index >= s.length()) {
perms.push_back("");
return perms;
}

std::string key = s.substr(index, 1);
std::vector<:string> prev = permute(s, index + 1);
for (size_t i = 0; i std::string p = prev[i];
for (size_t j = 0; j std::string n = p.insert(j, key);
perms.push_back(n);
p = prev[i];
}
}
return perms;
}

int main()
{
std::string name = "12345";
std::vector<:string> perms = permute(name, 0);
for (auto& p : perms) {
std::cout }
}

12345
21345
23145
23415
23451
13245
....



Viewing all articles
Browse latest Browse all 31

Latest Images

Trending Articles



Latest Images