用栈来模拟递归的技巧
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<cstring> #include<set> #include<algorithm> #include<stack> #include<string> #include<cstdio> #define _for(i, a, b) for (int i = (a); i<(b); ++i) using namespace std; struct problem { int n; char scr, mid, dest; problem(int nn, char s, char m, char d) :n(nn), scr(s), mid(m), dest(d) {} }; stack<problem> stk; int main() { int n; cin >> n; stk.push(problem(n, ‘A‘, ‘B‘, ‘C‘)); while (!stk.empty()) { problem now = stk.top(); stk.pop(); if (now.n == 1) { cout << now.scr << "->" << now.dest << endl; } else { stk.push(problem(now.n - 1, now.mid, now.scr, now.dest));//先放最后一个子问题 stk.push(problem(1, now.scr, now.mid, now.dest)); stk.push(problem(now.n - 1, now.scr, now.dest, now.mid)); } } system("pause"); }