题解 | 火车进站

火车进站

https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109

回溯法

#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

vector<vector<int>> out_order;
vector<int> path;

void backTrack(int index, vector<int>& order, stack<int>& st) {
    if(path.size() == order.size() && st.empty()) {
        out_order.push_back(path);
        return ;
    }

    //将当前火车入站
    if(index < order.size()) {
        st.push(order[index]);
        backTrack(index + 1, order, st);
        st.pop();
    }

    //将栈顶火车出站
    if(!st.empty()) {
        int train = st.top();
        st.pop();
        path.push_back(train);
        backTrack(index, order, st);
        st.push(train);
        path.pop_back();
    }
}

int main() {
    int n;
    cin >> n;
    stack<int> st;
    vector<int> order(n);
    for (int i = 0; i < n; ++i) {
        cin >> order[i];
    }
    out_order.clear();
    path.clear();
    backTrack(0, order, st);
    sort(out_order.begin(), out_order.end());
    for (auto& o : out_order) {
        for (int& i : o) {
            cout << i << " ";
        }
        cout << endl;
    }
    return 0;
}

全部评论
点赞 回复 分享
发布于 03-09 09:15 上海

相关推荐

野猪不是猪🐗:现在的环境就是这样,供远大于求。 以前卡学历,现在最高学历不够卡了,还要卡第一学历。 还是不够筛,于是还要求得有实习、不能有gap等等... 可能这个岗位总共就一个hc,筛到最后还是有十几个人满足这些要求。他们都非常优秀,各方面都很棒。 那没办法了,看那个顺眼选哪个呗。 很残酷,也很现实
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务