题解 | #火车进站#

火车进站

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

package org.example.test.practice;

import com.alibaba.fastjson.JSONObject;

import java.util.*;

public class Main { static List<List> all = new ArrayList<>(); static LinkedList path = new LinkedList<>();

// 先回溯算出所有的排列,在检查出站顺序是否合理
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNextInt()) {
        int n = scanner.nextInt();
        int[] num = new int[n];
        for (int i = 0; i < n; i++) {
            num[i] = scanner.nextInt();
        }
        dfs(num);
        List<List<Integer>> ans = new ArrayList<>();
        for (List<Integer> list : all) {
            if (check(num, list)) {
                ans.add(list);
            }
        }
        Collections.sort(ans, new Comparator<List<Integer>>() {
            @Override
            public int compare(List<Integer> o1, List<Integer> o2) {
                String a = "";
                for (int i = 0; i < o1.size(); i++) {
                    a += o1.get(i);
                }
                String b = "";
                for (int i = 0; i < o2.size(); i++) {
                    b += o2.get(i);
                }
                return a.compareTo(b);
            }
        });
        for (List<Integer> list : ans) {
            for (int i = 0; i < list.size(); i++) {
                System.out.print(list.get(i) + " ");
            }
            System.out.println();
        }
    }
}

private static boolean check(int[] num, List<Integer> list) {
    Deque<Integer> stack = new LinkedList<>();
    int j = 0;
    for (int i = 0; i < num.length; i++) {
        stack.push(num[i]);
        while (!stack.isEmpty() && stack.peek() == list.get(j)) {
            j++;
            stack.pop();
        }
    }
    return stack.isEmpty();
}

private static void dfs(int[] num) {
    if (path.size() == num.length) {
        all.add(new ArrayList<>(path));
        return;
    }
    for (int i = 0; i < num.length; i++) {
        if (!path.contains(num[i])) {
            path.add(num[i]);
            dfs(num);
            path.removeLast();
        }
    }
}

}

全部评论
思路一样,这种时间应该会相对较长吧
点赞 回复 分享
发布于 2022-04-11 15:23

相关推荐

11-08 17:36
诺瓦科技_HR
点赞 评论 收藏
分享
小红书 后端开发 总包n+8w+期权
点赞 评论 收藏
分享
评论
1
1
分享
牛客网
牛客企业服务