模拟,dfs
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int n, cnt = 20;
vector<int> state1;
stack<int> state2;
int state3 = 1;
void dfs()
{
if(!cnt) return;
if(state1.size() == n)
{
cnt--;
for(auto x : state1) cout<<x;
cout<<endl;
return;
}
if(state2.size())
{
state1.push_back(state2.top());
state2.pop();
dfs();
// 恢复现场
state2.push(state1.back());
state1.pop_back();
}
if(state3<=n)
{
state2.push(state3);
state3 ++;
dfs();
state3 --;
state2.pop();
}
}
int main()
{
cin >> n;
dfs();
return 0;
}
解法二
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
int n;
vector<int> a;
// 判断出栈顺序是否合法
bool check()
{
stack<int> s;
queue<int> q;
for(int i = 0; i < n; i++) q.push(a[i]);
for(int i = 1; i <= n; i++)
{
s.push(i);
while(!s.empty() && s.top()==q.front()) s.pop(), q.pop();
}
if(s.size()==0) return true;
else return false;
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
a.push_back(i);
int cnt = 0;
do
{
if(check())
{
for(int i = 0; i < n; i++) cout << a[i];
cout << endl;
cnt++;
if(cnt==20) break;
}
}while(next_permutation(a.begin(), a.end()));
return 0;
}
作者:虹之间
链接:https://www.acwing.com/solution/acwing/content/7484/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。