mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-08 18:49:07 +01:00
47 lines
1.2 KiB
C++
47 lines
1.2 KiB
C++
#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;
|
|
}
|