For learning purposes, I've written an iterative version of a recursive algorithm for generating the set of permutations for a given set of unique integers.
Can I make any improvements to increase readability and performance?
I've also read in various sources that when transforming a recursive algorithm into an iterative one, the stack data-structure is often used to 'substitute' the call stack used in the recursive case. I'm not using a std::stack
here but could I have used one to simplify my implementation?
using std::vector; vector<vector<int>> permutations(vector<int> integers) { vector<vector<int>> curr_perms; if (integers.size() <= 1) { curr_perms.push_back(integers); return curr_perms; } size_t sz = integers.size(); vector<vector<int>> next_perms; // initialise with the one permutation of the last single element vector<int> t = { integers[sz - 1] }; curr_perms.emplace_back(t); // backwards iterating a sequence of at least two elements for (int i = sz - 2; i >= 0; --i) { auto first = integers[i]; for (const auto &s : curr_perms) { for (auto j = 0U; j < s.size() + 1; ++j) { vector<int> p(s.begin(), s.end()); // make a copy p.insert(p.begin() + j, first); // shuffle in 'first' element next_perms.push_back(std::move(p)); // and add this as a new permutation } } // permutations found in this iteration are the input for the next std::swap(next_perms, curr_perms); // <-- is this needlessly copying all the elements? next_perms.clear(); } return curr_perms; }