入栈序列为
{1,2,...,n}
使用C++语言实现如下
#include <iostream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
stack<char> stack1;
string s;
vector<string> ans;
int n = 4;
void f(int x)
{
// three ifs can be exchanged.
if (!stack1.empty()) {
s += to_string(stack1.top());
stack1.pop();
f(x);
stack1.push(s[s.size() - 1] - '0');
s = s.substr(0, s.size() - 1);
}
if (x <= n) {
stack1.push(x);
f(x + 1);
stack1.pop();
}
if (x > n && stack1.empty()) {
ans.push_back(s);
}
}
int main()
{
f(1);
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << endl;
}
}