思想:1、利用全排列函数next_permutation()求出所有可能的序列
2、从中选出所有正确的序列
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
//判断序列是否是合法的出栈序列
bool IsPopOrder(const int* pPush,const int* pPop,int n)
{
if (pPush == NULL || pPop == NULL || n == 0)
return false;
int i = 0;
int j = 0;
stack<int> s;
while (i < n){
if (!s.empty() && pPop[j] == s.top()){
s.pop();
++j;
}
else{
s.push(pPush[i++]);
}
}
while (j<n && pPop[j] == s.top()){
s.pop();
++j;
}
if (j == n )
return true;
else
return false;
}
int main()
{
vector<int> vPush;
vector<int> vPop;
int n = 0;
cin >> n;
int tmp = 0;
for (int i = 0; i < n; ++i){
cin >> tmp;
vPush.push_back(tmp);
vPop.push_back(tmp);
}
sort(vPush.begin(),vPush.end());
int count = 0;
//循环判断所有的序列是否合法
while(1){
int* pPush = &vPush[0];
int* pPop = &vPop[0];
count += IsPopOrder(pPush, pPop, n);
if (next_permutation(vPop.begin(), vPop.end()) == false)
break;
}
cout << count << endl;
system("pause");
return 0;
}《完》
本文出自 “零蛋蛋” 博客,谢绝转载!
原文:http://lingdandan.blog.51cto.com/10697032/1851430