I have an assignment to implement a nonrecursive permutation algorithm using a stack ADT. The explanation to the problem includes a recursive algorithm that I don't understand:

#include <iostream> #include <vector> using namespace std; void gen(vector<int> & permutation, int level, int n) //What is the function of the 'level' variable? { int i; if(level==n) { for(i=0;i<n;i++) cout<<permutation[i]; cout<<endl; } else { for(i=0;i<=level;i++) { vector<int> p(permutation); //What does this do? p.insert(p.begin()+i,level); //And what is happening here? gen(p,level+1,n); } } } int main() { int n; cin>>n; vector<int> permutation; gen(permutation,0,n); return 0; }

I've put the things that I don't understand as notes in the code.

I would also appreciate it if someone could help me how to begin with the problem. I've implemented my own stack ADT but don't know how to go about the problem proper. I also don't understand how to use stack in the algorithm.

Any help is much appreciated!