#include #include #include #include #include template bool nextPermutation(std::vector &vec) { // Find non-increasing suffix if (vec.empty()) return false; typename std::vector::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::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 permutations(std::string s) { std::set strings; std::vector result; std::vector 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; }