3 ms·
I prefer the use of iterators, instead of generating a whole collection. An example of a permutation iterator in C++ is: class Permutations { publi
by fjfaase 9y ago
I prefer the use of iterators, instead of generating a whole collection. An example of a permutation iterator in C++ is:
class Permutations
{
public:
Permutations(int val_n) : n(val_n), _more(true)
{
a = new int[n];
for (int i = 0; i < n; i++)
a[i] = i;
}
~Permutations()
{
delete []a;
}
bool more() { return _more; }
void next()
{
_more = false;
for (int i = n-2; i >= 0; i--)
if (a[i] < a[i+1])
{
_more = true;
for (int j = n-1; j > i; j--)
if (a[j] > a[i])
{
swap(a[j], a[i]);
break;
}
i++;
for (int j = n-1; j > i; j--, i++)
swap(a[j], a[i]);
break;
}
}
int operator[](int i) { return a[i]; }
int n;
private:
void swap(int &x, int &y)
{
int h = x;
x = y;
y = h;
}
bool _more;
int *a;
};