全排列判断栈序火车进出站
Posted 松狮MVP
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了全排列判断栈序火车进出站相关的知识,希望对你有一定的参考价值。
1、全排列:
(1)递归实现:
void myFullSort(vector<int> data, int k, int end)
int i;
if (k == end)
for (i = 0; i <= end; i++)
cout << data[i] << " ";
cout << endl;
else
for (i = k; i <= end; i++)
std::swap(data[k], data[i]);
myFullSort(data, k + 1, end);
std::swap(data[k], data[i]);
(2)非递归实现:
(3)运用STL中的函数next_permutation( ):
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
//STL —— next_permutation()
void permutation(vector<int> array, int len)
sort(array.begin(), array.end()); //必须首先对原始数据进行排序,否则无法得到全部的全排列()
do
for (int i = 0; i < len; ++i)
cout << array[i] << " ";
cout << endl;
while (next_permutation(array.begin(), array.end())); //next_permutation是根据数字大小在找下一个排列
int main()
vector<int> a = 3, 2, 1, 4 ;
permutation(a, a.size());
return 0;
(4)如果数据中有重复数字,则需要剔除重复的全排列序列:
bool IsSwap(vector<int>& pszStr, int nBegin, int nEnd)
for (int i = nBegin; i < nEnd; i++)
if (pszStr[i] == pszStr[nEnd])
return false;
return true;
void myFullSort(vector<int> data, int k, int end)
int i;
if (k == end)
for (i = 0; i <= end; i++)
cout << data[i] << " ";
cout << endl;
else
for (i = k; i <= end; i++)
if (IsSwap(data, k, i))
std::swap(data[k], data[i]);
myFullSort(data, k + 1, end);
std::swap(data[k], data[i]);
2、判断栈序:
bool isPopsort(vector<int> Push, vector<int> Pop)
size_t size1 = Push.size();
size_t size2 = Pop.size();
if (size1 == 0 || size2 == 0)
return false;
stack<int> tmp; //辅助栈
for (size_t i = 0, j = 0; i < size1; i++)
tmp.push(Push[i]);//如果不是出栈序列元素,就一直压栈
while (j < size2 && !tmp.empty() && Pop[j] == tmp.top()) //开始判断
tmp.pop();
j++;
return tmp.empty();
3、火车进出站:(上面两者的组合)
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
vector<int> input;
bool isPopsort1(vector<int> Push, vector<int> Pop)
size_t size1 = Push.size();
size_t size2 = Pop.size();
if (size1 == 0 || size2 == 0)
return false;
stack<int> tmp; //辅助栈
for (size_t i = 0, j = 0; i < size1; i++)
tmp.push(Push[i]);//如果不是出栈序列元素,就一直压栈
while (j < size2 && !tmp.empty() && Pop[j] == tmp.top()) //开始判断
tmp.pop();
j++;
return tmp.empty();
void myFullSort1(vector<int> data, int k, int end)
int i;
if (k > end)
if (isPopsort1(input, data)) //全排列必须是栈序,才可以输出
for (i = 0; i <= end; i++)
cout << data[i] << " ";
cout << endl;
else
for (i = k; i <= end; i++)
std::swap(data[k], data[i]);
myFullSort1(data, k + 1, end);
std::swap(data[k], data[i]);
int main()
int N;
cin >> N;
for (int i = 0; i < N; i++)
int tmp;
cin >> tmp;
input.push_back(tmp);
myFullSort1(input, 0, N - 1);
return 0;
以上是关于全排列判断栈序火车进出站的主要内容,如果未能解决你的问题,请参考以下文章