1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 19:19:07 +01:00
CodeWars/4kyu/permutations/solution.cpp

48 lines
1.2 KiB
C++
Raw Normal View History

#include <algorithm>
#include <iostream>
#include <set>
#include <string>
#include <vector>
template <typename T> bool nextPermutation(std::vector<T> &vec) {
// Find non-increasing suffix
if (vec.empty())
return false;
typename std::vector<T>::iterator i = vec.end() - 1;
while (i > vec.begin() && *(i - 1) >= *i)
--i;
if (i == vec.begin())
return false;
// Find successor to pivot
typename std::vector<T>::iterator j = vec.end() - 1;
while (*j <= *(i - 1))
--j;
std::iter_swap(i - 1, j);
// Reverse suffix
std::reverse(i, vec.end());
return true;
}
std::vector<std::string> permutations(std::string s) {
std::set<std::string> strings;
std::vector<std::string> result;
std::vector<char> s_vec;
// copy string into vector
for (auto ch = s.begin(); ch != s.end(); ch++) {
s_vec.push_back(*ch);
}
// do the magic
std::sort(s_vec.begin(), s_vec.end());
do {
strings.insert(std::string(s_vec.begin(), s_vec.end()));
} while (nextPermutation(s_vec));
std::copy(strings.begin(), strings.end(), std::back_inserter(result));
return result;
}