火车进站(HJ77)
一:解题思路
这道题目比较难,不是数组的全排列,和数组的全排列有点类似,可以放在一起学习。需要仔细阅读题目才能够比较好的理解,其本质就是考察栈数据结构以及对它的后进先出特性的理解。Time:O(n^2),Space:O(n)
二:完整代码示例 (C++版和Java版)
C++代码:
#include <iostream> #include <vector> #include <stack> #include <algorithm> using namespace std; bool isOutNum(vector<int>& push, vector<int>& pop) { if (push.size() == 0 || pop.size() == 0) return false; stack<int> stack; int j = 0; for (int i = 0; i < push.size(); i++) { stack.push(push[i]); while (j < pop.size() && !stack.empty() && pop[j] == stack.top()) { stack.pop(); j++; } } return stack.empty(); } int main() { int n = 0; while (cin >> n) { vector<int> pushNum(n,0); vector<int> popNum(n,0); for (int i = 0; i < n; i++) { cin >> pushNum[i]; popNum[i] = pushNum[i]; } sort(popNum.begin(),popNum.end()); do { if (isOutNum(pushNum, popNum)) { for (int i = 0; i < popNum.size(); i++) { cout << popNum[i] << " "; } cout << endl; } } while (next_permutation(popNum.begin(),popNum.end())); } return 0; }

浙公网安备 33010602011771号