题解 | #火车进站#
火车进站
https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
递归和遍历一起用上,,,
#include <iostream> #include <bits/stdc++.h> using namespace std; int N; vector<vector<int>> ChuS(vector<int> Jin, vector<int> Zhan, vector<int> Chu) { vector<vector<int>> Chustras; Chustras.clear(); if (Jin.empty() && Zhan.empty()) { if (Chu.size() == N) { Chustras.push_back(Chu); } } else if (Jin.empty() && !Zhan.empty()) { int nT = Zhan.back();//出站 Zhan.pop_back(); Chu.push_back(nT); vector<vector<int>> ChustrasT; ChustrasT = ChuS(Jin, Zhan, Chu); auto itB = ChustrasT.begin(); auto itE = ChustrasT.end(); Chustras.insert(Chustras.end(), itB, itE); } else if (!Jin.empty() && Zhan.empty()) { int nT = Jin.front();//进站 Jin.erase(Jin.begin(), Jin.begin()+1); Zhan.push_back(nT); vector<vector<int>> ChustrasT; ChustrasT = ChuS(Jin, Zhan, Chu); auto itB = ChustrasT.begin(); auto itE = ChustrasT.end(); Chustras.insert(Chustras.end(), itB, itE); } else if (!Jin.empty() && !Zhan.empty()) { vector<int> Jin1, Zhan1, Chu1;//多选,进站或出站 int nT1 = Jin.front(); //进站 Jin1 = Jin; Jin1.erase(Jin1.begin(), Jin1.begin()+1); Zhan1 = Zhan; Zhan1.push_back(nT1); Chu1 = Chu; int nT = Zhan.back();//出站 Zhan.pop_back(); Chu.push_back(nT); vector<vector<int>> ChustrasT, ChustrasT1; ChustrasT1 = ChuS(Jin1, Zhan1, Chu1); ChustrasT = ChuS(Jin, Zhan, Chu); auto itB1 = ChustrasT1.begin(); auto itE1 = ChustrasT1.end(); auto itB = ChustrasT.begin(); auto itE = ChustrasT.end(); Chustras.insert(Chustras.end(), itB1, itE1); Chustras.insert(Chustras.end(), itB, itE); } return Chustras; } int count = 0; int main() { cin >> N; vector<int> Jin(N, 0); for (int i = 0; i < N; ++i) { cin >> Jin[i]; } vector<vector<int>> chuStras; vector<int> Zhan, Chu; Zhan.clear(); Chu.clear(); chuStras = ChuS(Jin, Zhan, Chu); int len = chuStras.size(); int len2=chuStras[0].size(); map<string ,string > ZiDpai; for (int i = 0; i < len; ++i) { string arow; arow.clear(); for (int j = 0; j < len2; j++) { int ouT = chuStras[i][j]; string strT; strT=to_string(ouT); arow.append(strT); if(j==len2-1){ break; } arow.push_back(32);//空格32 or \0 } pair<string,string> pT(arow,arow); ZiDpai.insert(pT); } for(auto it=ZiDpai.begin();it!=ZiDpai.end();++it){ string out=it->first; cout<<out<<endl; } return 0; } // 64 位输出请用 printf("%lld")