1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include<iostream> #include<vector> #include<stack> using namespace std;
class Permutation_traversal{ protected: vector<int>left_index; stack<pair<vector<int>::iterator,int>>visitstack; vector<int>::iterator iter; Permutation_traversal(const vector<int>&li,const stack<pair<vector<int>::iterator,int>>&vs) :left_index(li),visitstack(vs){ iter = left_index.begin(); } public: Permutation_traversal(int s){ for(int i=0;i<s;i++){ left_index.push_back(i); } iter = left_index.begin(); } bool const empty(){ return left_index.empty(); } void next(){ if(iter == left_index.end()) return ; ++iter; }
bool const valid(){ return iter != left_index.end(); }
int getnum(){ return visitstack.size(); }
int const getvalue(){ return iter != left_index.end() ? *iter : -1; } void push(){ if(iter == left_index.end()) return ; visitstack.push(make_pair(iter,*iter)); left_index.erase(iter); } void pop(){ if(visitstack.empty()) return ; pair<vector<int>::iterator,int> p = visitstack.top(); left_index.insert(p.first,p.second); visitstack.pop(); }
Permutation_traversal * isolate(){ return new Permutation_traversal(left_index,visitstack); } };
void ptdemo(Permutation_traversal & pt){ if(pt.empty()) return ; for(;pt.valid();pt.next()){ int debug = pt.getvalue(); pt.push(); Permutation_traversal * child_pt = pt.isolate(); ptdemo(*child_pt); delete child_pt; pt.pop(); } return ; } int main(){ Permutation_traversal pt(10); ptdemo(pt); return 0; }
|